Laravel: Get Object From Collection By Attribute

前端 未结 9 1701
暖寄归人
暖寄归人 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:31

    Elegant solution for finding a value (http://betamode.de/2013/10/17/laravel-4-eloquent-check-if-there-is-a-model-with-certain-key-value-pair-in-a-collection/) can be adapted:

    $desired_object_key = $food->array_search(24, $food->lists('id'));
    if ($desired_object_key !== false) {
       $desired_object = $food[$desired_object_key];
    }
    

提交回复
热议问题