@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.
@aniya.jaskolski
This Laravel code snippet showcases how to filter a collection efficiently using the filter method. Here's a breakdown of the process:
This process demonstrates a straightforward way to filter collections in Laravel by applying a specified condition for selection.