Laravel dynamic property not working

3k views Asked by At

I'm using the eloquent ORM in Laravel with a hasMany relationship.

when I run:

Level::find(1)->lessons()->get();

It works fine, but when I use the dynamic property like so:

Level::find(1)->lessons

It just returns results for the level instead of the lessons.

Do I need another setting somewhere?

EDIT: Here are the models:

class Level extends Eloquent {

    protected $table = 'levels';

    public function lessons()
    {
        return $this->hasMany('Lesson');
    }
}

class Lesson extends Eloquent {

    protected $table = 'lessons';

    public function level()
    {
        return $this->belongsTo('Level');
    }
}
2

There are 2 answers

3
Ezra On

I just had the same problem, turns out I had a column on the table that had the same name as the relationship I set up.

Make sure you don't have a column in the model that has the same name as the relationsip method you are trying to load.

EDIT: I also noticed laravel has problems with undescores (_) in relationship names, so don't put an _ in the methodname or else it won't work.

0
tharumax On

You need to eager load the relationship.

Level::with('lessons')->find(1)->lessons; should work.

If you want to load this relationship every time, you should add this line to Level model.

protected $with = array('lessons');