phplaraveleloquentcollections

Add Element at First Index of Collection


I have a collection of FamilyMember and I want to add a new element to the first Index of this collection, and I want to know How I could achieve this?

$family_members = FamilyMember::all();

$tmp_all_members = new FamilyMember();
$tmp_all_members->id = "all_family_member";
$tmp_all_members->name = "All Family Member";

$family_members [] = $tmp_all_members

but it adds a new element at the end of the collection. I have tried array_unshift but it throws the error:

array_unshift(): Argument #1 ($array) must be of type array, Illuminate\Database\Eloquent\Collection given

Solution

  • Laravel has awesome documentation. You can find what you're looking for here: https://laravel.com/docs/9.x/collections#available-methods

    Collections have a prepend method that will add an item to the beginning of the collection:

    $family_members->prepend($tmp_all_members);