Posts Learn Components new Snippets new Categories Tags 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

44 views

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.

Introduction


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.
<?php

// 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]

Post::query()
    ->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);
    })
    ->get();
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.
\DB::table('posts')
    ->when(/* your condition*/);
new

If you like our tutorial, do make sure to support us with some coffee. We need the juice to write the content during the night 🤙🏻