
Replace if-else with laravel When Condition. Traditionally we use to write lots of if-else conditions for checking if the value matches and then write some SQL query. But from now if you are on Laravel, it lot easier and looks prettier.
No more if-else condition, Laravel provide when() method for doing that all.
Let’s first see the traditional if-else condition
if (request('filter_by') == 'username') {
$query->where('username', 'like', '%'.request('username').'%');
}
if (request('filter_by') == 'email') {
$query->Where('email', 'like', '%'.request('email').'%');
}
in the Above block, we are checking if filter_by post has username then search data by username and if filter_by post has email then search by email.
Now, let’s go with Laravel When(), you will love it
$query = User::latest();
$query->when(request('filter_by') == 'username', function ($q) {
return $q->where('username', request('username'));
});
$query->when(request('filter_by') == 'email', function ($q) {
return $q->where('email', request('email'));
});
$users = $query->get();
Looks much better and easier to read. It’s the same as if-else but more readable and easier.
Hope this helped you.


Leave a Reply