Yes, you can achieve this using Laravel's collection methods. You can use the max method to find the maximum value and then use the first method to retrieve the corresponding item. Here's how you can do it:
$collection = collect([
['foo' => 10, 'bar' => ['value' => 50, 'code' => 1]],
['foo' => 20, 'bar' => ['value' => 40, 'code' => 2]],
]);
$maxValue = $collection->max('bar.value');
$maxItem = $collection->first(function ($item) use ($maxValue) {
return $item['bar']['value'] === $maxValue;
});
$barContent = $maxItem['bar'];
print_r($barContent);
This will output:
Array
(
[value] => 50
[code] => 1
)
Explanation:
- We first find the maximum value in the nested
bar.valueusing themaxmethod. - We then use the
firstmethod to find the first item in the collection wherebar.valuematches the maximum value. - Finally, we extract the
barcontent from the item with the maximum value.
This approach ensures that you get the bar content for the item with the highest bar.value in a clean and efficient manner.