teacher
has a one-to-many relationship with the course
.
course
belongs to one teacher
.
student
can participate in several courses
.
course
can include several students
.
According to Laravel standards, I also wrote the interface and relation table in the model.
Now I want to get the number of students of a teacher in TeachersController
And if possible, get a list of his students.
public function course()
{
return $this->hasMany(course::class);
}
public function teacher()
{
return $this->belongsTo(Teacher::class);
}
public function students()
{
return $this->belongsToMany(Student::class)
->withPivot('start_date', 'cancel_date', 'status');
}
public function courses()
{
return $this->belongsToMany(course::class)
->withPivot('status', 'start_date', 'cancel_date');
}
I tried to get the list and number of students through the course model defined in the teacher relation to the student model defined in the course model. But Laravel makes a mistake.
public function show(Teacher $teacher)
{
$countStudent = $teacher->course()->get()->students();
dd($countStudent);
}
You can use hasManyThrough relationship here
Teacher.php
public function students() {
return $this->hasManyThrough(Student::class, Course::class);
}
in your controller
public function show(Teacher $teacher){
$countStudent = $teacher->students()->count();
dd($countStudent);
}