condition

Eloquent::when(): No More if-elses for Conditional Queries

For a while many of us used to write conditional queries with “if-else”, something like this:

What if I told you there’s a (much) better way? Easily readable and more Laravel-ish. Meet when() method.

Looks nicer, doesn’t it?

Wait, there’s more

In the example below we will filter users only if the role was passed as a request option.

This means – as long as there is no parameter or it’s false/null – you will see all of the users but if it becomes a value, lets say “1” for administrator – you will only see administrators.

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

More information about conditional queries: https://laravel.com/docs/5.5/queries#conditional-clauses

Here’s a pull request for the parameter acceptance (not mentioned in official docs): https://github.com/laravel/framework/pull/18419

Want more tips and articles like this?
20-50 useful links every week on our weekly newsletter - comes out every Thursday!



One thought on “Eloquent::when(): No More if-elses for Conditional Queries

Leave a Reply

Your email address will not be published. Required fields are marked *