John Davidson

php - Laravel collection filter to return data based on condition

0 comments
Message:


I wonder if it's possible to filter a laravel collection based on a specific attribute value.


[
{
"id": 2,
"perm_id": 1,
},
{
"id": 3,
"perm_id": 1,
},
{
"id": 10,
"perm_id": 2,
},
{
"id": 9,
"perm_id": 1
}
]

This is how the structure of my collection looks like. I have multiple objects with the same perm_id. I need to return the object with the highest id for each perm_id. So the final return value should be like:


[
{
"id": 10,
"perm_id": 2,
},
{
"id": 9,
"perm_id": 1
}
]


My Answer:
Yes, it is possible to filter a Laravel collection based on a specific attribute value using the `filter` method. Here is an example of how you can achieve this:

php
$collection = collect([
['name' => 'John', 'age' => 30],
['name' => 'Jane', 'age' => 25],
['name' => 'Bob', 'age' => 35],
]);

$filteredCollection = $collection->filter(function ($item) {
return $item['age'] > 30;
});

$filteredCollection->all();


In this example, we have a collection of arrays with 'name' and 'age' attributes. We use the `filter` method to only keep the items where the 'age' attribute is greater than 30. The resulting `$filteredCollection` will only contain the item with 'Bob' as the name.

You can adjust the condition inside the `filter` callback function to filter the collection based on any attribute value you need.

Rate this post

4 of 5 based on 7022 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us