Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get key values from a collection in Laravel

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading