hasMany Relationship not working

Posted 11 months ago by JokersMild85

A workout has many workout_exercises:

Workout Model:

class Workout extends Model
{
    //
    protected $fillable = [
        'user_id',
        'name',
        'published_at'
    ];
    
    public function workout_exercises()
    {
        return $this->hasMany('App\WorkoutExercise');
    }
    
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

A workout_exercise belongs to a workout

Workout_Exercise Model

class WorkoutExercise extends Model
{
    //
    protected $fillable = [
        'workout_id',
        'exercise_id',
        'we_set_num',
        'we_rep_num',
        'we_set_complete',
    ];
    
    public function workout(){
        return $this->belongsTo('App\Workout');
    }

    public function exercise(){
        return $this->belongsTo('App\Exercise');
    }
}

When I define my $workout object and then run the following statement, I receive a 'trying to get property on non-object' error

$workout->workout_exercises->get();

Any suggestions?

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.