In Laravel, if I perform a query:
$foods = Food::where(...)->get();
...then $foods
is an Illuminate Collection of Foo
Use the built in collection methods contain and find, which will search by primary ids (instead of array keys). Example:
if ($model->collection->contains($primaryId)) {
var_dump($model->collection->find($primaryId);
}
contains() actually just calls find() and checks for null, so you could shorten it down to:
if ($myModel = $model->collection->find($primaryId)) {
var_dump($myModel);
}
I have to point out that there is a small but absolutely CRITICAL error in kalley's answer. I struggled with this for several hours before realizing:
Inside the function, what you are returning is a comparison, and thus something like this would be more correct:
$desired_object = $food->filter(function($item) {
return ($item->id **==** 24);
})->first();
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;
});
Since I don't need to loop entire collection, I think it is better to have helper function like this
/**
* Check if there is a item in a collection by given key and value
* @param Illuminate\Support\Collection $collection collection in which search is to be made
* @param string $key name of key to be checked
* @param string $value value of key to be checkied
* @return boolean|object false if not found, object if it is found
*/
function findInCollection(Illuminate\Support\Collection $collection, $key, $value) {
foreach ($collection as $item) {
if (isset($item->$key) && $item->$key == $value) {
return $item;
}
}
return FALSE;
}
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');