If you want to filter a 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 .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 of writing this post here: Collection#l214-260

Source link


Please enter your comment!
Please enter your name here