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
}
]
3
Answers
This is find in the documentation of Laravel:
Using a map function you can filter by an atribute value.
https://laravel.com/docs/9.x/collections
You can group all items by
perm_id
and then map them to get the highestid
.Try this->
Output: