Laravel 8.x, 3 models and many to many relationship

  eloquent, laravel, many-to-many, pivot

I am new to laravel and trying the following:

I have these tables:

disciplines: id | name

specialties: id | name

categories: id | name

discipline_specialty (pivot table): id | discipline_id | specialties_id

Discipline model:

public function specialties()
        return $this->belongsToMany(Specialty::class);

Specialty model:

public function disciplines()
        return $this->belongsToMany(Discipline::class);

My question is:

how can I relate (many to many) the categories to the pivot table discipline_specialty in order to access the category name with the discipline and specialty ids?
I had thought of an additional pivot table that linked category id and discipline_specialty id but I don’t know if it’s the best solution and how to do it. Do you have any suggestions? Any help is appreciated.

Source: Laravel

Leave a Reply