Search code examples
laraveleloquentsubquery

How to get the counts of Student for each Teachers in a single collection by Eloquent


A Teacher has many Students. When I am showing the Teachers list I also want to show the counts of Student for each Teachers. How can I do this by using Eloquent?

I can find the Teachers from this, $teacher= Teacher::where('teacher_status','active')->get();

I can find the Student count from this $student_count = Student::where('teacher_id','teachers.id')->count();

How can I conbine this two query and return the response in a single array/collection?


Solution

  • In your teacher model, create the relationship students:

    class Teacher extends Model
    {
        public function students()
        {
            return $this->hasMany(Student::class, 'teacher_id');
        }
    }
    

    In your controller you can do the following:

    public function example(){
        $teachers = Teacher::where('teacher_status','active')->withCount('students')->get();
        
        return view('teacherViewExample', compact('teachers'));
    }
    

    In your view (teacherViewExample):

    <table>
      <thead>
        <tr>
          <th>Teacher Name</th>
          <th>Students Count</th>
        </tr>
      </thead>
      <tbody>
        @foreach($teachers as $teacher)
        <tr>
          <td>{{ $teacher->name }}</td>
          <td>{{ $teacher->students_count }}</td>
        </tr>
        @endforeach
      </tbody>
    </table>
    

    Full documentation on how to use withCount() here: https://laravel.com/docs/9.x/eloquent-relationships#counting-related-models

    Sometimes you may want to count the number of related models for a given relationship without actually loading the models. To accomplish this, you may use the withCount method. The withCount method will place a {relation}_count attribute on the resulting models: