Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel rename collection keys

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

like image 579
Skywarth Avatar asked Sep 01 '25 16:09

Skywarth


1 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.

like image 71
Saeid Asadi Avatar answered Sep 04 '25 07:09

Saeid Asadi