Laravel Collections Filter Method Example; In ths tutorial you will learn you how to use collection filter method in laravel application. The filter() method filters the collection using the given callback, keeping only those items that pass a given truth test.
Laravel collection filter uses for method by key, by value and remove null and empty values. 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, run the strtoupper
function on each element, and then remove all empty elements:
We have added 3 best examples to understand and use the laravel collections filter so you can understand easily.
Example 1:
public function index(Request $request){
$collection = collect([1, 2, 3, 4]);
$results = $collection->filter(function ($value, $key) {
return $value > 2;
});
echo "<pre>"; print_r($results); die;
}
Output:
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[2] => 3
[3] => 4
)
)
If no callback is supplied, all entries of the collection that are equivalent to false
will be removed:
Example 2:
public function index(Request $request){
$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 3:
public function index(Request $request){
$collection = collect([
['name' => 'Test 1', 'age' => null],
['name' => 'Test 2', 'age' => 14],
['name' => 'Test 3', 'age' => 28],
['name' => 'Test 4', 'age' => 84],
]);
$filtered = $collection->filter(function ($item) {
return data_get($item, 'age') >= 28;
});
$results = $filtered->all();
dd($results);
}
Output:
array:2 [▼
2 => array:2 [▼
"name" => "Test 3"
"age" => 28
]
3 => array:2 [▼
"name" => "Test 4"
"age" => 84
]
]
I hope it will help you..