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:

Here’s a pull request for the parameter acceptance (not mentioned in official docs):

Want to generate Laravel adminpanel online?
You don't need any packages to do that!

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 *