Jared Meyering
Jared Meyering

Reputation: 1321

Laravel 4 Eager Loading in Many to Many Relationship

Trying to do a simple eager load with Laravel 4 using a many to many relationships. My Models look like.

class Facility extends Eloquent {

    public function photos(){
            return $this->belongsToMany('Photo');
    }
}

class Photo extends Eloquent {

    public function facilities(){
            return $this->belongsToMany('Facility');
    }
}

Tabes are set up according to Laravel standards. When I try to load using

$facilities = Facility::with('Photo')->get();

I end up with a Laravel error

Call to undefined method Illuminate\Database\Query\Builder::photo()

Any idea whats being done wrong here?

Upvotes: 1

Views: 1976

Answers (1)

Homme Sauvage
Homme Sauvage

Reputation: 1916

You should try:

$facilities = Facility::with('photos')->get();

Remember, the argument you are passing to with() is the method, not the model, so if you have another method in the model, say: location(), you'll call:

$facilities = Facility::with(['photos', 'location'])->get();

Upvotes: 6

Related Questions