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

Desarrollo con Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz en Udemy

Acepto recibir anuncios de interes sobre este Blog.

!Cursos a!

10$

En Udemy

Quedan 4 días!

Udemy

!Cursos desde!

4$

En Academia

Ver los cursos

!Libros desde!

1$

Ver los libros
¡Hazte afiliado en Gumroad!
!Web Alojada en Hostinger!