What is the difference between Model :: lists () and Model :: all () - lists () in Laravel?

3

In Laravel , we have a method that we can list fields of a table in the key-value style.

I can do this in two ways

So:

Usuario::lists('nome', 'id');

And So:

Usuario::all()->lists('nome', 'id');

The result would be:

 [1 => 'Wallace', 2 => 'Guilherme', 3 => 'Bigown', 4 => 'Miguel']

But since there are two ways to do this, what is the difference between the two?

    
asked by anonymous 17.02.2016 / 11:47

1 answer

3

Well, the difference is this: When you invoke lists you make only the specified fields specified in the Orm of laravel query and put them back into a array .

Example:

Usuario::lists('nome', 'id');

It's the same as:

SELECT nome, id FROM usuarios

As for the all method followed by lists , something else happens. When we call Usuario::all() we get all results in the usuarios table and with all the selected fields.

SELECT * FROM usuários

The all method will return an object called Illuminate\Database\Eloquent\Collection . This object, in turn, has the all method. But internally, it uses the function called array_pluck to capture only the two past items, such as key and value.

Performance

The difference in performance is noticeable between the two explanations. lists gained in both the query execution and the amount of data brought to PHP.

If you are just bringing a list containing the key-value pair of the bank, you should use lists .

However, there are cases where, in addition to bringing complete user data, for reasons of necessity of a particular type, you would like to transform a Eloquent\Collection object into a array .

In this case, we are talking about a concept of object orientation called Reuse.

An example of this is that you need to bring all user data to a table listing, but at the same time you need to list those users in a select (you will need to use lists in that collection so you do not make another SELECT on the bank).

I'll give you an example:

 $usuario = Usuario::all();

 // Preciso da lista de nomes e ids para passar para um "select" no html

$usuarios_lista = $usuarios->lists('nome', 'id');
    
17.02.2016 / 13:46