Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add an item into a Laravel Eloquent Collection by index?

I tried the following but it doesn't work.

$index = 2;
$collection->put($index, $item4);

For example if $collection looks like this:

$collection = [$item1, $item2, $item3];

I'd like to end up with:

$collection = [$item1, $item2, $item4, $item3];
like image 689
rotaercz Avatar asked Dec 02 '22 18:12

rotaercz


2 Answers

The easiest way would probably be to splice it in, like this:

$collection->splice(2, 0, [$item4]);

Collections usually support the same functionality as regular PHP arrays. In this case, it's the array_splice() function that's used behind the scenes.

By setting the second parameter to 0, you essentially tell PHP to "go to index 2 in the array, then remove 0 elements, then insert this element I just provided you with".

like image 96
Joel Hinz Avatar answered Dec 06 '22 11:12

Joel Hinz


To elaborate a little on Joel's answer:

  • splice modifies original collection and returns extracted elements
  • new item is typecasted to array, if that is not what we want we should wrap it in array

Then to add $item at index $index:

$collection->splice($index, 0, [$item]);

or generally:

$elements = $collection->splice($index, $number, [$item1, $item2, ...]);

where $number is number of elements we want to extract (and remove) from original collection.

like image 25
Paul Avatar answered Dec 06 '22 10:12

Paul