Sia Sia - 4 days ago 5
PHP Question

retrieve data from 3 tables How to retrieve data from the last table using the first one in Larvel

I have three table:

Teacher

id

name

family_name

ClassRoom

class_name

teacher_id

Student

name

family_name

Teacher have one to many relation with ClassRoom

Student have many to many relation with ClassRoom

how can i retrieve all Students of a Teacher using Eloquent methods without using foreach?

Answer
$teacher = Teacher::with('classrooms.students')->find($someId); //eager load
$studentsArray = $teacher->classrooms->pluck('students'); //array of students with duplicates
$students = (new Collection($studentsArray))->collapse()->unique(); //collection of unique students
Comments