I don't know if it's the best or right way to do it, but in PHP, I simply would.
$array = [];
$array['CODE-123'][] = [
'name' => 'NAME 001',
'lastname' => 'LASTNAME 001',
];
$array['CODE-456'][] = [
'name' => 'NAME 004',
'lastname' => 'LASTNAME 004',
];
$array['CODE-123'][] = [
'name' => 'NAME 002',
'lastname' => 'LASTNAME 002',
];
$array['CODE-456'][] = [
'name' => 'NAME 005',
'lastname' => 'LASTNAME 005',
];
But the point is: How to proceed to get the same result but using Laravel Collection? That is, how can I add/append new elements using the 'desired key' from a Laravel Collection?
If I try to use the put()
, it overwrites the original key content.
$collection = collect();
$collection->put('CODE-123', [
'name' => 'NAME 001',
'lastname' => 'LASTNAME 001',
]);
$collection->put('CODE-456', [
'name' => 'NAME 004',
'lastname' => 'LASTNAME 004',
]);
For example, I want to add some new items, in the key 'CODE-123', if it were a native PHP array, I would use a pair of square brackets, but using collection, I couldn't and it generates an ErrorException (E_NOTICE) Indirect modification of overloaded element.
$collection['CODE-123'][] = 'some new item...';