How to use Eloquent::when() in Laravel
In this, tutorial we will discuss How to use Eloquent::when() in Laravel. Lararave Eloquent::when(): No More if-else for Conditional Queries. Laravel Eloquent::when() use is no more if-else for conditional queries. Laravel default provides Eloquent::when(). While many of us used to write conditional if-else queries.
Also read: Laravel Eloquent updateOrCreate Query Example
If-else
if (request('filter') == 'likes') {
$query->where('likes', '>', '1');
}
if (request('filter') == 'date') {
$query->orderBy('created_at', 'DESC');
}
And we are discussing in this tutorial, Eloquent::when() query. and you there a better way? Easily readable and more Laravel.
Eloquent::when()
$query = User::query();
$query->when(request('filter') == 'asc', function ($q) {
return $q->where('likes', '>', '1');
});
$query->when(request('filter') == 'date', function ($q) {
return $q->orderBy('created_at', 'DESC');
});
$users = $query->get();
Eloquent::when()
$query = User::query();
$query->when(request('role', false), function ($q, $role) {
return $q->where('role_id', $role);
});
$users = $query->get();