Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel-eloquent: Call to undefined method Illuminate\Database\Eloquent\Collection::where()

I have two models in many-to-one relationship:

class Meal extends \Eloquent {
    /**
     * public Integer   $id; - primary key
     * public String    $name;
     */
    protected $fillable = array('id','name');

    public function mealProperties()
    {
        return $this->hasMany('MealProperty');
    }
}

class MealProperty extends \Eloquent {
    /**
     * public Integer   $id; - primary key
     * public Integer   $meal_id;
     */
    protected $fillable = array('id','meal_id');

    public function meal()
    {
        return $this->belongsTo('Meal', 'meal_id');
    }
}

if I ask for first meal first mealProperty everything go fine:

$mealProp = Meal::first()->mealProperties->first();

but if I ask for mealProperty with specific id of first meal this way:

$mealProp = Meal::first()->mealProperties->where('id','=','1')->first();

I get this error:

Call to undefined method Illuminate\Database\Eloquent\Collection::where()

I google what I'm doing wrong two hours, but still nothing.

If I can't use where method, what is possible way to get specific mealProperty?

Thank you for help!

like image 595
Martin Filek Avatar asked Apr 08 '14 18:04

Martin Filek


2 Answers

UPDATE for Laravel 5:

Since v5 release there is a method where on the Support\Collection object, so this question/answer becomes irrelevant. The method works exactly like filter, ie. returns filtered collection straight away:

$mealProp = Meal::first()->mealProperties->where('id','=','1'); // filtered collection

// that said, this piece of code is perfectly valid in L5:
$mealProp = Meal::first()->mealProperties->where('id','=','1')->first();

You must distinguish Laravel behaviour:

(dynamic property) Eloquent Collection or Model

$meal->mealProperties

Relation Object

$meal->mealProperties()

Now:

// mealProperties is Eloquent Collection and you call first on the Collection here
// so basically it does not affect db query
$mealProp = Meal::first()->mealProperties->first();

// here you try to add WHERE clause while the db query is already called
$mealProp = Meal::first()->mealProperties->where('id','=','1')->first();

// So this is what you want to do:
$mealProp = Meal::first()->mealProperties()->where('id','=','1')->first();
like image 126
Jarek Tkaczyk Avatar answered Oct 27 '22 00:10

Jarek Tkaczyk


You may try this:

$mealProop1 = Meal::first()->mealProperties->find(1); // id = 1

Or something like this:

$mealProops = Meal::first()->mealProperties;
$mealProop5 = $mealProops->find(5); // id = 5
$mealProop7 = $mealProops->find(7); // id = 7

Instead of this:

$mealProp = Meal::first()->mealProperties->where('id','=','1')->first();

Also, following should work:

$mealProp = Meal::first()->mealProperties->first();
like image 33
The Alpha Avatar answered Oct 27 '22 00:10

The Alpha