Using IF Condition Inside a query in Laravel

The task for me today was to filter the products as per their status i.e if they are published then their value would be 1 and if they are unpublished then their value would be 0. But I didn’t want to create three queries for them, one for each condition. Therefore, I used the if condition inside query like this.

But I didn’t have an answer to what to do to get all the products whatever their status maybe so I kept the else field empty.

The code is down below. I passed the $status variable which has either ‘published’ or ‘unpublished’ or ‘all’ condition.

return Product::where(function($query) use ($status)  {
                if($status == 'published') {
                    $query->where('product_status', 1);
                elseif ($status == 'unpublished'){
                    $query->where('product_status', 0);
                else {

I hope this helps you too.

1 thought on “Using IF Condition Inside a query in Laravel”

Leave a Comment

Your email address will not be published. Required fields are marked *