DEV Community

Rohit Urane
Rohit Urane

Posted on

2

How to use eloquent when in laravel

Image description

In this article, We are implementing laravel eloquent when condition. In the filter-out process, we use the if-else condition on request. Check the code below.



if($request->filter_by == 'amount')
{
    $query->where('amount', '>', request('amount', 0));
}

if($request->filter_by == 'created_at')
{
    $query->orderBy('created_at', request('order', 'desc'));
}


Enter fullscreen mode Exit fullscreen mode

How to use eloquent when in laravel

You can use the when() method. It is more readable and user-friendly. Check the code below.



$query = Order::query();

$query->when(request('filter_by') == 'amount', function($q){
    return $q->where('amount','>', request('amount',0));
});
$query->when(request('filter_by') == 'created_at', function($q){
    return $q->orderBy('created_at', request('order','desc'));
});



Enter fullscreen mode Exit fullscreen mode

You can pass the third argument to the when method. This closure will only execute if the first argument evaluates as false.



$query = Order::query();
$query->when(request('filter_by') == 'amount', function($q){
    return $q->where('amount','>', request('amount',0));
}, function($q){
    return $q->orderBy('created_at', request('order','desc'));
})->get();


Enter fullscreen mode Exit fullscreen mode

It's not just a prettier way to write the same "IF" but is also a great way to organize conditional queries.

You can read more about this type of article on the site

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay