Home > Enterprise >  Get key values from a collection in Laravel
Get key values from a collection in Laravel

Time:12-17

I have this collection

1 => {#27
       "id": 1
       "name": "Zel"
       "age": "43"
    }
2 => {#28
       "id": 2
       "name": "Kol"
       "age": "56"
    }
3 => {#29
       "id": 3
       "name": "Mil"
       "age": "32"
    }

and I would like to return an array with the key values as a string like this:

[
'id',
'name',
'age',
]

Can someone help me with that, please?

CodePudding user response:

use array_keys :

$keys = array_keys($collection->first());

CodePudding user response:

Laravel collection has a keys() method you could simply use it like this:

$keys = $collection->keys();
$get = $keys->all();

It is all clearly written in the Laravel Documentation

EDIT

After looking at your edit, my first consideration would be that if your collection is consistent you could get the first one and subsequently get the keys from there on:

$keys = $collection->first();
$get = $keys->keys()->all();

Or simply put $collection->first()->keys()->all();

EDIT

Here is how i was able to reproduce your problem:

$collection = collect([
    [
        'id' => 1, 
        'name' => 'Zel',
        'age' => 43
    ],
    [
        'id' => 2, 
        'name' => 'Kol',
        'age' => 56
    ],
    [
        'id' => 3, 
        'name' => 'Mil',
        'age' => 32
    ],
]);
$keys = collect($collection->first())->keys()->all();

Here is the Result I got:

array:3 [▼
  0 => "id"
  1 => "name"
  2 => "age"
]

If it still returns a collection or an object based on your last comment, you could try any one of these:

$keys = $keys->toArray();
$keys = collect($keys)->toArray();
  • Related