Advanced operations with Collection::where in Laravel 5.3

(This is part of a series of posts on New Features in Laravel 5.3.)

  1. Introducing Laravel Echo: An In-Depth Walk-Through
  2. The new $loop variable in Laravel 5.3
  3. Customizing additional parameters in FirstOrCreate in Laravel 5.3
  4. The new cache() global helper in Laravel 5.3
  5. New JSON-column where() and update() syntax in Laravel 5.3
  6. Advanced operations with Collection::where in Laravel 5.3
  7. Image dimension validation rules in Laravel 5.3
  8. Customizing pagination templates in Laravel 5.3
  9. 5.3 feature announcement notes from Laracon
  10. Routing changes in Laravel 5.3
  11. Introducing Laravel Scout
  12. Introducing Laravel Passport
  13. Introducing Mailables in Laravel 5.3
  14. Directory structure changes in Laravel 5.3
  15. The new Notification system in Laravel 5.3
  16. Update to queue workers in Laravel 5.3
  17. Using Vue in Laravel 5.3, with the Vue bootstrap and sample component
  18. Defining console commands via closure in Laravel 5.3 (coming soon)

If you want to filter a Laravel collection to only those records which meet particular criteria, you're most likely going to reach for filter() or reject(). For a quick refresh, this is how you might use both:

$vips = $people->filter(function ($person) {
    return $person->status === 'vip';

$nonVips = $people->reject(function ($person) {
    return $person->status === 'vip';

You might not know it, but there's also a where() method that's pretty simple that gives you the same functionality:

$vips = $people->where('status', 'vip');

Prior to 5.3, this would check strictly (===), just like in our examples above.

In 5.3, that same line is now a loose check (==), but you can also customize the comparison operator. That makes all of this possible:

$nonVips = $people->where('status', '!==', 'vip');
$popularPosts = $posts->where('views', '>', 500);
$firstTimeUsers = $people->where('logins', '===', 1);

You can see the all of the possible operators at the time of writing this post here: Collection#l214-260

Comments? I'm @stauffermatt on Twitter

Tags: laravel | laravel 5.3

Matt Stauffer headshot

Hi, I'm Matt Stauffer.

I'm partner & technical director at Tighten Co.

You can find me on Twitter at @stauffermatt

Like what you're reading?

I wrote an entire 450+ page book for O'Reilly: Laravel: Up and Running.

You can order the eBook or print book today.