Using Laravel Pivot Table

Rafa Rafael
Mar 1, 2019 · 2 min read

For the sake of simplicity I will define a 3 tables, which is the student, teacher & classroom then having a schema that look like below:

Student’s Table

id | name | timestamps

Teacher’s Table

id | name | timestamps

Classroom’s Table

id | section_name | student_id | teacher_id | timestamps

As you can see, the student’s & teacher’s table doesn’t have foreign key to define a relationship between them. One of the reason is, for example we want to keep the record of the students’ teacher each year, so if we put the teachers_id in the student’s table, this will be close to impossible since it will always update the column every school year.

So to make things easier you store the relationship between the student and the teacher in another table and that is the classroom table or much better name :).

Alright! let start, I assume you already had student and teacher model, so we will now create our model called… — of course Classroom then the code will look like this.

What’s this? Assuming you are not using route model binding

$student = Student::findOrFail($request->studentId);

$teacher = Teacher::findOrFail($request->teacherId);

If you want to save a student and teacher in the pivot table you can now use.

$teacher->students()->save($student, ['student_id' => $student->id]);

or

$teacher->students()->attach($student->id);

If you want to remove the student under the teacher you can easily use the

$teacher->students()->detach($student->id);

or

$teacher->students()->detach() to remove all students to the teacher

if you want to get all students of this teacher

$teacher->students()->get();

If you want to get a student of this teacher

$teacher->students()->where('id', $student->id)->first();

That’s it! We can make our reports in no time. Enjoy!

Rafa Rafael

Written by

More From Medium

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade