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

扶醉桌前 提交于 2019-12-04 01:31:03
Matt Burrow

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.

The put method sets the given key and value in the collection:

$collection = collect(['product_id' => 1, 'name' => 'Desk']);

$collection->put('price', 100);

$collection->all();

// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!