I have a collection of objects. Let's say the objects are tags:
$tags = Tag::all();
I want to retrieve a certain attribute for each tag, say its name. Of course I can do
foreach ($tags as $tag) {
$tag_names[] = $tag->name;
}
But is there a more laravelish solution to this problem?
Something like $tags->name
?
Yep, you can do it nice and easily. As the Laravel 4 Documentation states, you can do
Retrieving All Rows From A Table
Retrieving A Single Row From A Table
Retrieving A Single Column From A Row
Retrieving A List Of Column Values
This method will return an array of role titles. You may also specify a custom key column for the returned array:
Specifying A Select Clause
EDIT:
The above examples show how to access data with the help of Laravel's fluent query builder. If you are using models you can access the data with Laravel's Eloquent ORM
Because Eloquent is internaly using the query builder, you can without any problem do the following things:
which could be also done with:
Here are a few snippets from my own experimentation on the matter this morning. I only wish (and maybe someone else knows the solution) that the Collection had a $collection->distinct() method, so I could easily generate a list of column values based on an already filtered collection.
Thoughts?
I hope these snippets help clarify some alternative options for generating a list of unique values from a Table, Collection, and Eloquent Model.
Using a Collection (Happy)
Using an Eloquent Model (Happier)
Using an Eloquent Model PLUS Caching (Happiest)
I would love to hear some alternatives to this if you guys have one!
@ErikOnTheWeb
You could use
array_column
for this (it's a PHP 5.5 function but Laravel has a helper function that replicates the behavior, for the most part).Something like this should suffice.
Collections have a
lists
method similar to the method for tables described by @Gadoma. It returns an array containing the value of a given attribute for each item in the collection.To retrieve the desired array of names from my collection of tags I can simply use:
Update: As of laravel 5.2
lists
is replaced bypluck
.More specifically, the laravel 5.2 upgrade guide states that "[t]he
lists
method on the Collection, query builder and Eloquent query builder objects has been renamed topluck
. The method signature remains the same."