Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

krookroo's avatar

eloquent relationship between 3 tables

I wanna get the director of a movie using this tables

movie -mov_id -mov_title

director -dir_id -dir_name

movieDirection -mov_id -dir_ID

I cant figure it out especially because Im new to eloquent relationship. Should I make 3 models for each tables?

0 likes
6 replies
krookroo's avatar

their relationship would be like this: movie has one/many movieDirection and movieDirection has one movie directorhas one/many movieDirection and movieDirection has one director

SilenceBringer's avatar

hi @luigi213

What you really need is pivot table.

So, you'll have 3 tables

movies: id, title directors: id, name director_movie (table name following the convention): movie_id, director_id

and you just need to have 2 models: Movie and Director with the following relations:

class Movie extends Model
{
    public function directors()
    {
        return $this->belongsToMany(Director::class);
    }
}


class Director extends Model
{
    public function movies()
    {
        return $this->belongsToMany(Movie::class);
    }
}

If you prefer to use your own tables and columns names, you will need to fill foreign key and owner key in relation declaration

1 like
krookroo's avatar

I see. How will I pull out the data I need? and how will the printing in the blade.php be? I wanna get the director of a specific movie.

SilenceBringer's avatar
dd($movie->directors);

will returns to you collection of associated directors. You can do everything you need with it

<h3>Directors</h3>
@foreach ($movie->directors as $director)
    <div>{{ $director->name }}</div>
@endforeach

this example will output list of directors associated with the given movie

SilenceBringer's avatar
Level 55

@luigi213

Calling "pivot" returns you data from intermediate table. By the way, you need to specify the data you want to load from intermediate table manually on relations (only keys are included in pivot by default).

class Movie extends Model
{
    public function directors()
    {
        return $this->belongsToMany(Director::class)->withPivot('date');
    }
}


class Director extends Model
{
    public function movies()
    {
        return $this->belongsToMany(Movie::class)->withPivot('date');
    }
}

echo $movie->directors->first()->pivot->date;

1 like

Please or to participate in this conversation.