How to filter collection in laravel?

by aniya.jaskolski , in category: PHP Frameworks , 5 days ago

How to filter collection in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by edmond_brakus , 4 days ago

@aniya.jaskolski 

In Laravel, you can filter a collection using the filter method. Here is an example of how you can filter a collection of items in Laravel:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
$collection = collect([
    ['name' => 'John', 'age' => 30],
    ['name' => 'Jane', 'age' => 25],
    ['name' => 'Bob', 'age' => 35],
]);

$filteredCollection = $collection->filter(function ($item, $key) {
    return $item['age'] > 20; // Filter items where age is greater than 20
});

$filteredCollection->values(); // Reset the keys of the collection

// Output the filtered collection
$filteredCollection->each(function ($item) {
    echo $item['name'] . ' - ' . $item['age'] . "
";
});


In this example, we have a collection of items with names and ages. We use the filter method to filter out items where the age is greater than 20. Finally, we output the filtered collection.

Member

by kadin , 4 days ago

@aniya.jaskolski 

This Laravel code snippet showcases how to filter a collection efficiently using the filter method. Here's a breakdown of the process:

  1. We create a Laravel collection using the collect helper function, containing an array with information about individuals (name and age).
  2. The filter method is employed on the collection to iterate over each item. It takes a closure function as an argument, which is executed for each key-value pair in the collection. In this case, we filter items where the age is greater than 20.
  3. The filteredCollection object now contains only the items that pass the filter condition.
  4. The values method is applied to reset the keys of the collection, ensuring that the filtered collection's keys are consecutive.
  5. Finally, we use the each method on the filteredCollection to iterate over each item and output their names and ages.


This process demonstrates a straightforward way to filter collections in Laravel by applying a specified condition for selection.