Series This post is in a series on New Features in Laravel 5.3.

Advanced operations with Collection::where in Laravel 5.3

Posted on July 8, 2016

!
Warning: This post is over a year old. I don't always update old posts with new information, so some of this information may be out of date.

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


This is part of a series of posts on New Features in Laravel 5.3:

  1. Jun 16, 2016 | laravel, laravel 5.3, echo, websockets
  2. Jun 27, 2016 | laravel, laravel 5.3
  3. Jun 29, 2016 | laravel, laravel 5.3, eloquent
  4. Jul 6, 2016 | laravel, laravel 5.3
  5. Jul 8, 2016 | laravel, laravel 5.3, eloquent
  6. Jul 25, 2016 | laravel, laravel 5.3
  7. Jul 26, 2016 | laravel, laravel 5.3
  8. Jul 27, 2016 | laravel, laravel 5.3, laravel scout, laravel passport, mailable
  9. Jul 27, 2016 | laravel, laravel 5.3, routing
  10. Jul 29, 2016 | laravel, laravel 5.3, laravel scout
  11. Jul 30, 2016 | laravel, laravel 5.3, laravel passport, oauth
  12. Aug 5, 2016 | laravel, laravel 5.3, mail, laravel mailables
  13. Aug 8, 2016 | laravel, laravel 5.3
  14. Oct 19, 2016 | laravel, laravel 5.3, laravel notifications, notifications
  15. Dec 21, 2016 | laravel, laravel 5.3, queues
  16. Dec 21, 2016 | laravel, laravel 5.3, vuejs, vueify, authorization
  17. Jan 30, 2017 | laravel, laravel 5.3, artisan

Subscribe

Quick links to fresh content, and more thoughts that don't make it to the blog