In Laravel, if I execute a request:
$foods = Food::where(...)->get();
... then $foods is an Illuminate Collection of Food model objects. (This is essentially an array of models.)
However, the keys of this array are simple:
[0, 1, 2, 3, ...]
... therefore, if I want to change, say, a Food object with an id of 24, I cannot do this:
$desired_object = $foods->get(24); $desired_object->color = 'Green'; $desired_object->save();
... because it just changes the 25th element in the array, not the element with id of 24.
How to get one (or several) items from a collection by ANY attribute / column (for example, id / color / age / etc.)?
Of course I can do this:
foreach ($foods as $food) { if ($food->id == 24) { $desired_object = $food; break; } } $desired_object->color = 'Green'; $desired_object->save();
... but, it's just rude.
And of course I can do this:
$desired_object = Food::find(24); $desired_object->color = 'Green'; $desired_object->save();
... but this is even more rude because it makes an additional unnecessary request when I already have the desired object in the $foods collection.
Thanks in advance for any recommendations.
EDIT:
To be clear, you can call ->find() in the Illuminate collection without creating another query, but it only accepts the primary identifier. For example:
$foods = Food::all(); $desired_food = $foods->find(21);
However, there is still no clean (non-looping, non-querying) way to capture element (s) with an attribute from the collection, for example:
$foods = Food::all(); $green_foods = $foods->where('color', 'green');