Laravel Collections Filter Method Example

10-Apr-2023

.

Admin

Laravel Collections Filter Method Example

Hi Guys,

In ths example,I will learn you how to use collection filter method in laravel.you can easy to use the filter method in laravel.

The filter function takes a callback as an argument and run filter over each item. If the test fails for a particular item, then it will remove it from the collection.

The Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data.We'll use the collect helper to create a new collection instance from the array.

Example 1:


/**

* The attributes that are mass assignable.

*

* @var array

*/

public function index()

{

$collection = collect([1, 2, 3, null, false, '', 0, [], 5, 6]);

$results = $collection->filter()->all();

dd($results);

}

Output :

array:5 [?

0 => 1

1 => 2

2 => 3

8 => 5

9 => 6

]

Example 2:

/**

* The attributes that are mass assignable.

*

* @var array

*/

public function index()

{

$collection = collect([

['name' => 'Ravi', 'age' => null],

['name' => 'Jaydev', 'age' => 14],

['name' => 'Sunil', 'age' => 23],

['name' => 'Hardik', 'age' => 84],

]);

$filtered = $collection->filter(function ($item) {

return data_get($item, 'age') >= 14;

});

$results = $filtered->all();

dd($results);

}

Output :

array:3 [?

1 => array:2 [?

"name" => "Jaydev"

"age" => 14

]

2 => array:2 [?

"name" => "Sunil"

"age" => 23

]

3 => array:2 [?

"name" => "Hardik"

"age" => 84

]

]

It will help you....

#Laravel

#Laravel 6