How to join a additional tables after pivot table join

I have a pivot table "show_user" with columns show_id, user_id

in my App\User.php i have

public function shows() {
    return $this->belongsToMany(Show::class);
}

in my App\Show.php i have

public function user(){
    return $this->belongsToMany(User::class);
}

i can call

App\User::find(1)->shows

and i get the list of shows associated with the user

now what i really want are the episodes attached to those shows, so i have set up in my App\Show.php

public function episodes()  {
    return $this->hasMany(ShowEpisode::class);
}

and in my App\ShowEpisode.php

public function show()  {
    return $this->belongsTo(Show::class);
}

but when i call

App\User::find(1)->shows->episodes

i get an error Property [episodes] does not exist on this collection instance.

how to fix this ? is it even possible to access the episodes like this ?

viiter
viiter
  • 1 month ago

It looks like Shows is a collection from your example, so if you access one of them, you can then get though to the episodes method. You can't access all of the episodes directly like your example.

For example, this below will get the episodes for the first show.

App\User::find(1)->shows->first()->episodes