Laravel: Get Object From Collection By Attribute

前端 未结 9 1711
暖寄归人
暖寄归人 2020-12-23 02:35

In Laravel, if I perform a query:

$foods = Food::where(...)->get();

...then $foods is an Illuminate Collection of Foo

9条回答
  •  悲哀的现实
    2020-12-23 03:18

    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;
    });
    

提交回复
热议问题