Posts Learn Components Snippets Categories Tags Tools new About

How to Conditionally Query Eloquent in Laravel

Learn how to conditionally query a record in Laravel using eloquent the easy and practical way

Created on Sep 29, 2021


In this short snippet, you will learn how to conditionally query a model in Laravel using Eloquent the easy way so let's get started.


Imagine you want to query a "Post" model and you want to provide a condition such as "filters" from the front-end. To achieve that you will have to conditionally add the condition/constrained if specified and otherwise query all of the records by default.

How to Define the Condition to Conditionally Query Eloquent in Laravel?

To conditionally query the model you can make use of the "when()" method available to every of your Model class. Do imagine querying the "Post" model that has a condition of "active post" and "posted by" constraint based on the condition that users have defined from the front-end filter. To do that you can write your code like the following.

// Do imagine that we access the condition from the "Request" class
$postStatus = request('post_status'); // 1 = active post
$postedBy = request('users_id'); // this can be multiple users id [1, 2, 3, etc]

    ->when(isset($postStatus), function ($query) use ($postStatus) {
        return $query->where('post_status', $postStatus);
    ->when(count($postedBy), function ($query) use ($postedBy) {
        return $query->whereIn('id', $postedBy);
Now that you have queried it like that, if the "post status" and "posted by" exists, the query will execute the "when" portion and have the condition applied.

Using DB Facade to Conditionally Query

Do note that you can also use the "DB" facade to conditionally perform the query just like using the Eloquent.
    ->when(/* your condition*/);

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for How to Conditionally Query Eloquent in Laravel


PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components