Conditional where clause in Laravel

Updated at 19-May-2021, By samar

Conditional where clause in Laravel

In this tutorial, we will try to find the solution to "Conditional where clause in Laravel" through programming.

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.
  • Filter rows of table with where clause in Laravel 8

    --PATH app\Http\Controllers\<PostController>.php
    <?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