Search code examples
phplaravellaravel-collection

How to convert object array to nested object by using Laravel Collection


I'm working on data assembling in a Laravel project. The data I could get from sql query is like this

[
  {
    "id": 1,
    "name": "John"
  },
  {
    "id": 2,
    "name": "Ben"
  }
]

I want to convert it to something like this,

{
  "1":{
    "name": "John"
  },
  "2":{
    "name": "Ben"
  }
}

Anyway elegant way to do it?


Solution

  • Use the keyBy collection method