Laravel: Get Object From Collection By Attribute

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

    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.

提交回复
热议问题