Laravel: Get Object From Collection By Attribute

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

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

提交回复
热议问题