There is a simple way to achieve what you propose, it goes like this according to the documentation :
Counting Related Models
If you want to count the number of results in a relationship without actually loading them, you can use the
method withCount
, which will place a column {relation} _count
in
its resulting models. For example:
$posts = App\Post::withCount('comments')->get();
foreach ($posts as $post) {
echo $post->comments_count;
}
Then, assuming that you have in Laravel your models Libro
and Materia
defined as well as the relation that joins them (in the model Materia
there is the method libros()
), applying to your case goes like this:
$materias = App\Materia::withCount('libros')->get();
In this way, you will have an additional column libros_count
that will indicate how many elements there are for each subject.
foreach ($materias as $materia) {
echo $materia->libros_count;
}