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.
Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter