Laravel collection filter() method is “used to filter the collection using the given callback, keeping only those items that pass a given truth test.”
Syntax
public function filter(callable $callback = null)
{
if ($callback) {
return new static(Arr::where($this->items, $callback));
}
return new static(array_filter($this->items));
}
The filter function takes a callback as an argument and runs a filter over each item. If the test fails for a particular item, it will be removed from the collection.
From now on, we will test each Laravel Collections Method inside the routes >> web.php file.
Example
Write the following code inside the web.php file.
<?php
// web.php
Route::get('/', function () {
$collection = collect([19, 21, 29, 46]);
$filtered = $collection->filter(function ($value, $key) {
return $value > 21;
});
dd($filtered->all());
});
We have checked each collection item against 21, and if any item > 21 is in the collection, it will be included in a new array.
Start the Laravel server by typing the following command in your project root.
php artisan serve
Go to http://localhost:8000, and you will see the following output.
That means it has created an array with all the items > 21. Rest items will be removed from the collection.
If no callback is supplied, all entries of the collection that are equivalent to false will be removed.
<?php
// web.php
Route::get('/', function () {
$collection = collect([0, 1, 2, 3, 4, 5]);
$filtered = $collection->filter();
dd($filtered->all());
});
In the above code, the 0 entry will be removed because it has been taken as a boolean 0, which is false. Thus, the output is the following.
That’s it for this tutorial.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.