Laravel rename collection keys

Viewed 4408

I have the following line to get an array of collections.

$tags = Tag::all()->map->only(['id', 'name']);

Which produces the following data.

[{"id":1,"name":"tag 2"},{"id":2,"name":"tag 3"},{"id":3,"name":"tag-44"},{"id":4,"name":"biyoloji"}]

My objective is to rename the key names inside the collections as follows.

[{"value":1,"text":"tag 2"},{"value":2,"text":"tag 3"},{"value":3,"text":"tag-44"},{"value":4,"text":"biyoloji"}]

Basically, I want to rename "key" to "value" and "name" to "text." I tried the pluck() function, get() function, mapping but couldn't get it to work. Most probably, iterating over it with foreach and toArray() would do the trick, but I'm looking for the proper way to do it. My environment is Laravel 8 with PHP 7.4

2 Answers

The best way I can propose:

$tags = Tag::query()->get(['id', 'name'])
   ->map(function($tag){
        return [
           'value' => $tag->id,
           'text' => $tag->name,
        ];
    })
    ->toArray();

Pay attention to get(['id', 'name]) invoking. Passing required fields to get method helps improving query performance. Specially if there are lots of unused columns in the table.

You can do this via your query more efficiently

$tags = Tag::get(['id as value', 'name as text']);
Related