Using count () in Laravel

1

I have controller that plays for my view the total number of courses registered in the portal. My doubts are due to the operation of the count() method.

For example, output of both statements below are equivalent:

1) Instruction

$usuario = User::find(Auth::id());
$usuario->cursos->count();

2) Instruction

Curso::count('id', Auth::id());

My question is, in statement 1 I am running a select fulltable , returning all the columns of the table and then passing to the count() method perform the count?

And the statement 2 , does it already mount a sql that executes count directly in the database returning only the total?

    
asked by anonymous 07.11.2016 / 13:14

1 answer

3
  

My question is, in statement 1 I'm running a select fulltable, returning all the columns of the table and then passing to the count () method to do the count?

In this first code 1 user of type User and with access to cursos collection and then count() classe collection is counted how many items in this collection. Actually here are 2 SQL , one retrieving the user and the other bringing the courses of that user ( unnecessary reading ). There is a problem instead of you accessing the relation, cursos() is accessed from the course collection ( reading, table data )) and this is quite wrong, need at the moment, when you use the data simply do:

$usuario = User::find(Auth::id());
$usuario->cursos()->count(); 

remains 2 SQL , but at least it does not load unnecessary table data.

  

And statement 2, does it already mount an sql that executes the count directly on the database returning only the total?

SQL is direct, only 1 SQL bringing the result by filter of the number of courses, relative to 1 is direct and becomes better.

  

In short:

The second is more optimized and objective and in the first you give two laps, because,

Auth::id()

could be:

Auth::user()->cursos()->count();

Since it is understood that the count of courses and the user logged in (or authenticated). In this line Auth::user()->cursos()->count(); is created 1 SQL for counting courses according to the logged in user.

    
07.11.2016 / 13:19