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?
3
Answers
If you want to count the number of students related to teacher without actually loading them you may use the withCount method and this add new propery named by a {relation}_count column on your resulting models. For example:
Also you need and to your Teacher model hasMany relation method to Students
In your teacher model, create the relationship students:
In your controller you can do the following:
In your view (teacherViewExample):
Full documentation on how to use
withCount()
here: https://laravel.com/docs/9.x/eloquent-relationships#counting-related-modelsIn case frontend and backend are separated, i.e Laravel for backend, Angular for frontend, below are examples for Laravel:
In api.php,
In Teacher.php (model)
In TeacherController.php