Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have read Dayle Rees's Code Bright to know more about Eloquent Collections used in Laravel. Did some other research as well but couldn't find the answer I was looking for.

I want to insert an object (Model type object) into a Collection Object at a specific position.

For example:

This is the returned collection

Illuminate\Database\Eloquent\Collection Object
(
    [0] => Attendance Object
        ([present_day] => 1)

    [1] => Attendance Object
        ([present_day] => 2)

    [2] => Attendance Object
        ([present_day] => 4) 

    [3] => Attendance Object
        ([present_day] => 5) 

)

As you can see above [present_day] have a values ranging from 1 to 5, but the value, 3 is missing in the sequence. Now, what I really want to do is, I want to explicitly put a new Attendance Object at the Collection Object's position of [2] index number/position, thus by pushing the rest of the Attendance Object. I am really struggling to do this right. How can I do this to make above collection object to look like something as below:

Illuminate\Database\Eloquent\Collection Object
(
    [0] => Attendance Object
        ([present_day] => 1)

    [1] => Attendance Object
        ([present_day] => 2)

    [2] => Attendance Object    // This is where new object was added.
        ([present_day] => 3) 

    [4] => Attendance Object
        ([present_day] => 4) 

    [5] => Attendance Object
        ([present_day] => 5) 

)

I think there is some methods that will allow to do exactly like this if it was array. Since this is a Collection, I am not sure how to do it.

Note: I don't want to convert it this to array and do the insertion within array. For some reason, I want to have this output strictly in Collection object.

like image 953
Nirmalz Thapaz Avatar asked Dec 10 '14 09:12

Nirmalz Thapaz


1 Answers

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.

like image 99
Matt Burrow Avatar answered Oct 05 '22 08:10

Matt Burrow