Laravel: Get Object From Collection By Attribute

前端 未结 9 1693
暖寄归人
暖寄归人 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: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');
    

提交回复
热议问题