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.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.

!Courses from!

10$

On Udemy

There are 3d 08:43!


Udemy

!Courses from!

4$

In Academy

View courses

!Books from!

1$

See the books
¡Become an affiliate on Gumroad!