Laravel: Get Object From Collection By Attribute

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

    Use the built in collection methods contain and find, which will search by primary ids (instead of array keys). Example:

    if ($model->collection->contains($primaryId)) {
        var_dump($model->collection->find($primaryId);
    }
    

    contains() actually just calls find() and checks for null, so you could shorten it down to:

    if ($myModel = $model->collection->find($primaryId)) {
        var_dump($myModel);
    }
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 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;
    });
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-23 03:26

    As from Laravel 5.5 you can use firstWhere()

    In you case:

    $green_foods = $foods->firstWhere('color', 'green');
    
    0 讨论(0)
提交回复
热议问题