Laravel: Get Object From Collection By Attribute

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

    As the question above when you are using the where clause you also need to use the get Or first method to get the result.

    /**
    *Get all food
    *
    */
    
    $foods = Food::all();
    
    /**
    *Get green food 
    *
    */
    
    $green_foods = Food::where('color', 'green')->get();
    
    0 讨论(0)
  • 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];
    }
    
    0 讨论(0)
  • 2020-12-23 03:35

    I know this question was originally asked before Laravel 5.0 was released, but as of Laravel 5.0, Collections support the where() method for this purpose.

    For Laravel 5.0, 5.1, and 5.2, the where() method on the Collection will only do an equals comparison. Also, it does a strict equals comparison (===) by default. To do a loose comparison (==), you can either pass false as the third parameter or use the whereLoose() method.

    As of Laravel 5.3, the where() method was expanded to work more like the where() method for the query builder, which accepts an operator as the second parameter. Also like the query builder, the operator will default to an equals comparison if none is supplied. The default comparison was also switched from strict by default to loose by default. So, if you'd like a strict comparison, you can use whereStrict(), or just use === as the operator for where().

    Therefore, as of Laravel 5.0, the last code example in the question will work exactly as intended:

    $foods = Food::all();
    $green_foods = $foods->where('color', 'green'); // This will work.  :)
    
    // This will only work in Laravel 5.3+
    $cheap_foods = $foods->where('price', '<', 5);
    
    // Assuming "quantity" is an integer...
    // This will not match any records in 5.0, 5.1, 5.2 due to the default strict comparison.
    // This will match records just fine in 5.3+ due to the default loose comparison.
    $dozen_foods = $foods->where('quantity', '12');
    
    0 讨论(0)
提交回复
热议问题