Home > OS >  Laravel Many to Many relationship for 3 tables
Laravel Many to Many relationship for 3 tables

Time:10-12

i've 3 tables Branches,Subjects,Teachers

Branches and subjects already many to many.

i've CRUD for teacher,when i create teacher i insert info to user model to add new user with type teacher.

i want to make relation to allow me combine teachers/branches/subjects.

for example when i'm creating teacher i need to select branch/branches and subject/subjects that this teacher related to.

any hint allows me to do this ?

CodePudding user response:

Its help you

< https://laracasts.com/discuss/channels/laravel/many-to-many-3-tables-1 >

and i it convert for you

If I get it right, you have established the many-to-many-relationships between every two of the three models

(Teacher, Branche & Subject).

Instead, you should establish the many-to many between any two models

of your choice and treat the third model as a pivot. For example:

Teacher.php

class Teacher extends Model

{

public function branches()

{

return $this->belongsToMany(Branche::class)->withPivot('subject');

}

}

Branche.php

class Branche extends Model

{

public function teachers()

{

return $this->belongsToMany(Teacher::class)->withPivot('subject');

} }

view.blade.php

@foreach($teachers as $teacher)

@foreach($teacher->branches as $branc)

{{ $branc->name }} {{ $branc->pivot->subject }}

@endforeach

@endforeach

  • Related