Laravel: Get Object From Collection By Attribute

前端 未结 9 1698
暖寄归人
暖寄归人 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条回答
  •  萌比男神i
    2020-12-23 03:21

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

提交回复
热议问题