May 7, 2017, midnight

Queries by Key in Laravel

By : Eric A. Scuccimarra

One of my greatest frustrations with Eloquent collections has been that I needed to loop through the collection and either create a new collection or array if I wanted to have the results in a format where I could access them by a value in the query results. That is to say if I want to be able to access the results by say primary key, I would need to loop through the Collection returned by the query and create a new object with the key as whatever I wanted it to be.

I just learned that there is a much easier way to do this: 

    Model::all()->keyBy('whatever');

This will return the collection with "whatever" as the key, which makes life so much easier and code so much cleaner.

Labels: coding , laravel

There are no comments for this article.

Login or register to comment