Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Jonjie's avatar
Level 12

How to use filter for a collection in laravel

Im trying to use filter() method for the collection in laravel 5.2. But the result returns the same result when I remove the filter() method. Please see my code below.

if(!empty(request('columns.1.search.value'))) {
   $union->filter(function($item) {
      return date_format(new \DateTime($item['SUBMITTED']), 'm/d/Y') == request('columns.1.search.value');
   });
}
0 likes
3 replies
Jonjie's avatar
Level 12

What if the collection has a key that I want to use? so example is the SUBMITTED key. Also the filtered value would be from request('columns.1.search.value')

Tray2's avatar
Tray2
Best Answer
Level 73

If you have a collection of arrays/collections you can do something like this

$filtered = $books->filter(function($value, $key) {
	if($value['title'] == 'The Great Hunt') {
		return $value;
    }
});

That will give you all the books with the title of The Great Hunt.

I take it you are getting the data you want to filter from the database? Then you should let the database do the filtering since it's way faster and uses way less resources.

Please or to participate in this conversation.