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

Question:

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

I can do this in two ways

So:

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

And so:

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

The result of this would be:

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

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

Answer:

Well, the difference is this: When you invoke lists you make only specific fields specified in laravel's Orm query and put them in an array .

Example:

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

It is the same as :

SELECT nome, id FROM usuarios

The case of the all method followed by lists is something else. When we call Usuario::all() we bring all existing results in the usuarios table and with all fields selected.

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 items passed, such as key and value.

performance

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

If you're just going to bring up a list containing the key-value pair from the bank, you should use lists .

However, there are cases where, in addition to bringing the complete user data, for reasons of need of a certain type, you would want to transform an Eloquent\Collection object into an array .

In this case, we are talking about an object-oriented concept called Reuse.

An example of this is needing to bring all user data to make a listing in a table, but at the same time needing a listing of these users in a select (then it will be necessary to use lists this collection, so as not to make another SELECT in the database).

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');
Scroll to Top