Laravel: Get Object From Collection By Attribute
You can use filter
, like so:
$desired_object = $food->filter(function($item) { return $item->id == 24;})->first();
filter
will also return a Collection
, but since you know there will be only one, you can call first
on that Collection
.
You don't need the filter anymore (or maybe ever, I don't know this is almost 4 years old). You can just use first
:
$desired_object = $food->first(function($item) { return $item->id == 24;});
Laravel provides a method called keyBy
which allows to set keys by given key in model.
$collection = $collection->keyBy('id');
will return the collection but with keys being the values of id
attribute from any model.
Then you can say:
$desired_food = $foods->get(21); // Grab the food with an ID of 21
and it will grab the correct item without the mess of using a filter function.
As from Laravel 5.5 you can use firstWhere()
In you case:
$green_foods = $foods->firstWhere('color', 'green');