How to insert an object (Model type object) into Collection Object in Laravel at specific index number?

To insert an item into a collection,refer to this answer; Answer

Basically, splits the collection, adds the item at the relevant index.


You can add the item to the Eloquent\Collection object with the add method;

$collection->add($item);  // Laravel 4

or

$collection->push($item); // Laravel 5 

Then you can reorder the collection using the sortBy method;

$collection = $collection->sortBy(function($model){ return $model->present_day; });

This will reorder the collection by your present_day attribute.


Note that the above code will only work if you are using Illuminate\Database\Eloquent\Collection. If you are using a plain Eloquent\Support\Collection, there is no add method.

Instead, you can use an empty array offset, the same as inserting a new element in a normal array:

$collection[] = $item;

This form also works on the Eloquent version of Collection.