How to filter a laravel collection?

Member

by denis , in category: PHP Frameworks , 4 months ago

How to filter a laravel collection?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , 4 months ago

@denis 

In Laravel, you can use the filter method to filter a collection based on a given callback function. Here's an example of how you can filter a Laravel collection:

  1. Retrieve a collection:
1
2
3
4
5
6
$collection = collect([
    ['name' => 'John', 'age' => 30],
    ['name' => 'Jane', 'age' => 25],
    ['name' => 'Bob', 'age' => 35],
    ['name' => 'Alice', 'age' => 40],
]);


  1. Use the filter method to filter the collection based on a condition. For example, let's filter the collection to only include people who are younger than 35:
1
2
3
4
5
6
$filteredCollection = $collection->filter(function ($item) {
    return $item['age'] < 35;
});

// Output the filtered collection
$filteredCollection->all();


In this example, the filter method takes a callback function that returns true if the item should be included in the filtered collection, and false if it should be excluded. The callback function is applied to each item in the collection.


You can also use the where method to filter a collection based on key-value pairs. For example, to filter the collection to only include people with the name 'Jane':

1
2
3
4
$filteredCollection = $collection->where('name', 'Jane');

// Output the filtered collection
$filteredCollection->all();


These are just a few examples of how you can filter a Laravel collection. There are many other methods available for filtering collections, so be sure to check out the Laravel documentation for more information.