Laravel Collections: when()

Don't if... when instead!
Posted By Ben - 16th May 2017

Laravel's Collections have many features that can save you time, including this little gem. No longer do you need to use un-eloquent (pun intended!) code to filter your queries.

Unless you scour the documentation it's easy to miss some of the handy methods that are available to you with all of Laravels libraries (Although you really should scour the documentation!). The handy when() method was brought to my attention on twitter by @calebporzio:

It's a fantastic way of filtering your query conditionally depending on your requirements, without having to resort to a single if(). Here's an example:

MyModel::when(request('email'), function($query, $email){
    $query->where('email', '=', $email);
})->get();

It's short and sweet while keeping your code as clean as could be... Enjoy! If you want to ready the entry on the docs visit: laravel.com/docs/5.4/collections#method-when