Laravel Collections “when” Method

Home » Laravel » Laravel Collections “when” Method
June 7, 2017 Laravel No Comments

Starting at v5.4.12, Laravel Collections now includes a when method that allows you to perform conditional actions on the items without breaking the chain.

Like all the other Laravel Collection methods this one can have a lot of use cases but one example that comes to mind is being able to filter based on a query string parameter.

To demonstrate that example, let’s pretend we have a list of hosts from the Laravel News Podcast:

Previously to filter based on a query string you might do something like this:

With the new when method you can now do this all in one Collection chain: