laraveleloquentquery-builderlaravel-relations

Obtain the number of students of a teacher


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.

Teacher Model

public function course()
{
    return $this->hasMany(course::class);
}

Course Model

public function teacher()
{
    return $this->belongsTo(Teacher::class);
}

public function students()
{
    return $this->belongsToMany(Student::class)
        ->withPivot('start_date', 'cancel_date', 'status');
}

Student Model

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);
}

Solution

  • 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);
    
    }