Using When Condition Inside a query in Laravel

Similar to the previous article I wrote about using the IF condition inside a query (Click Here for the link), I asked Reddit for the best way to handle the query in my previous article and I learned a bunch of ways where we can get the same solution. One of them using the when the condition is as follows:

If you want to go through the Reddit post, here is the link.

return Product::when($status === 'published', function ($query, $status) {
    return $query->where('product_status', 1);
})
    ->when($status === 'unpublished', function ($query, $status) {
    return $query->where('product_status', 0);
})
    ->get();

I wrote this article separately so that I can come back to this when I need it. I hope this also helps you.

Leave a Comment

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

Tweet
Share
Share
Pin