Hi , i have 4 tables
courses
students
teachers
course_student
courses has relation with students many to many throw course_student and i named this relation as subscription
#Courses Model
public function subscriptions()
{
return $this->belongsToMany(Student::class,'course_student','course_id');
}
and teacher has relation with courses throw teacher_id column that inside the courses table
#Teacher Model
public function courses() {
return $this->hasMany(Course::class);
}
Now i want to get all students for each teacher at his dashboard so i try with
public function students(): HasManyThrough
{
return $this->hasManyThrough(Student::class, Course::class, 'teacher_id', 'id');
}
and there's wrong data i collect from this relation , so i decided to make at as regular method like
public function students(): \Illuminate\Support\Collection
{
return collect($this->courses)->flatMap(function ($course){
return collect($course->subscriptions);
})->unique('id');
}
/**
flatmap to get all students at one collection cause regular map 'll create a collection for each course and each collection 'll has all students inside , and unique to filter all students and get the unique cause may the student has subscription at 2 or 3 courses for same teacher ,
*/
and now everything work correctly , but idk if this a laravel way or best practice or even clean code , so any recommendation ?