I believe you are doing something wrong. Take a look at this:
$users = collect([
(object)['id' => 5, 'value' => 30, 'something' => 'else'],
(object)['id' => 6, 'value' => 40, 'something' => 'else2'],
(object)['id' => 7, 'value' => 50, 'something' => 'else3'],
(object)['id' => 8, 'value' => 60, 'something' => 'else4'],
(object)['id' => 9, 'value' => 70, 'something' => 'else5'],
(object)['id' => 30, 'value' => 90, 'something' => 'else6'],
]);
$users = $users->mapWithKeys(function($user, $key) {
return [$user->id => $user];
});
dd($users);
The result here is:
Collection {#374
#items: array:6 [
5 => {#364
+"id": 5
+"value": 30
+"something": "else"
}
6 => {#363
+"id": 6
+"value": 40
+"something": "else2"
}
7 => {#362
+"id": 7
+"value": 50
+"something": "else3"
}
8 => {#361
+"id": 8
+"value": 60
+"something": "else4"
}
9 => {#356
+"id": 9
+"value": 70
+"something": "else5"
}
30 => {#357
+"id": 30
+"value": 90
+"something": "else6"
}
]
}
exactly as expected. Are you sure you don't display result using for example dd($users->values())
? Because values()
will remove those keys and in that case you will get indexes from 0 to 5.
It your case doesn't work, try with this - this should work and should give you idea what you are doing wrong.