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();
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*/);
Leave a reply