Laravel Eloquent: return the id or PK as key/key of the field in an array

- Andrés Cruz

En español

Laravel Eloquent: return the id or PK as key/key of the field in an array

Many times we need that in the array of a query returned by the database in Laravel, place a custom ID as the key or key of said array; usually puts an incrementing number, but we can customize this value; for that, we have to use the keyBy function that we have for free when using Eloquent on a query and with this we indicate the field that we want to customize as the key of the returned array; an example:

Model::all()->keyBy('id');

And with this we have:

 #items: array:2 [
    1 => App\Models\Category {#1250 }
    2 => App\Models\Category {#1251 }
  ]

Notice that the keys of the array correspond to the PK, that is, to the field called id

Instead of:

 #items: array:2 [
    0 => App\Models\Category {#1250 }
    1 => App\Models\Category {#1251 }
  ]

Which would be normal behavior.

I agree to receive announcements of interest about this Blog.

We can customize the returned array value in a list in Laravel using the keyBy function.

- Andrés Cruz

En español