Laravel 5 Collections: Filtering Collection Elements With filter

2 min read

The filter method applies a filter to the collection. An optional $callback can be supplied to the filter method. If no $callback is supplied to the filter method, any value in the collection that evaluates to false will be removed from the final collection. Supplying a $callback allows developers to provide their own truth tests to determine if a value should be included in the final collection that is returned.

The filter method returns a modified copy of the original Collection instance and does not modify the original collection.

Signature

1public function filter(
2 callable $callback = null
3);

Example Use

The following examples demonstrate the behavior of the filter method; the results of the filtering process will appear above the method invocation as a comment:

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 'first', 'second', '0', null
6]);
7 
8// ['first', 'second']
9$filtered = $collection->filter();
10 
11// ['0', null]
12$filtered = $collection->filter(function($item) {
13 return $item == false;
14});
15 
16// ['second']
17$filtered = $collection->item(function($item) {
18 return (strlen($item) >= 6);
19});

Using filter With Higher Order Messages

The filter method can also be used with higher order messaging, which allows us to invoke collection methods and access object instance properties using PHP's property accessors syntax. In the reject section, we implemented a Product class that was used to reject all products that were not on sale.

We will implement the same behavior using the filter method:

1$products = collect([
2 [
3 'name' => 'Office Chair',
4 'price' => 399.99,
5 'onSale' => false
6 ],
7 [
8 'name' => 'Desk',
9 'price' => 199.34,
10 'onSale' => true
11 ]
12])->transform(function ($item) {
13 $product = new Product;
14 $product->name = $item['name'];
15 $product->price = $item['price'];
16 $product->onSale = $item['onSale'];
17 
18 return $product;
19});
20 
21$onSale = $products->filter->isOnSale();

After the above code has been executed, the $onSale collection would contain one element, a Product instance representing the desk.

Thanks for taking the time to read this post! If you found this article useful and want to help support more work like this, please consider sponsoring my work on GitHub, or by checking out some merch.

 Sponsor on GitHub  Shop Merch