Count the records of a laravel pivot table


As I can count the records of a pivot table, I have the table libros and the table materias are already related to the pivot assigned_materias I would like to be able to obtain how many records there are per subject .

Do you know in any way?

I leave the tables




asked by Miguel Olea 14.08.2018 в 22:01

1 answer


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;
answered by 15.08.2018 / 01:04