"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to use eloquent when in laravel

How to use eloquent when in laravel

Published on 2024-07-31
Browse:184

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'));
}

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'));
});

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();

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

Release Statement This article is reproduced at: https://dev.to/rohiturane/how-to-use-eloquent-when-in-laravel-3b6b?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3