Conditional where clause in Laravel

Sometimes we need to filter records of tables based on input parameters. In that case, we can use conditional where clause in Laravel to filter the records with that particular input text.

Answers 1
  • Filter rows of table with where clause in Laravel 8

    --PATH app\Http\Controllers\<PostController>.php
    namespace App\Http\Controllers;
    use App\\Models\Post;
    use Illuminate\Http\Request;
    class PostController extends Controller{
            public function index(Request $request){
                $posts = Post::where('is_active', true);
                //Filter post by category_id
                if ($request->has('category_id') ) {
                    $posts->where('category_id', $request->category_id);
                //Filter post by created_at column
                if ($request->has('created_at')) {
                    $posts->where('created_at','>=', $request->created_at);
                return $posts->get();

    You can filter rows of tables using the where clause in Laravel. You have to check the request parameters if the request parameter exists then you can run the query with the where clause and after that you can get data using the get() method.

  • Back to code snippet queries related laravel