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
?
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:
$tags->lists('name');
Update: As of laravel 5.2 lists
is replaced by pluck
.
$tags->pluck('name');
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 to pluck
. The method signature remains the same."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With