Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading