Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two Laravel collections

My head hurts from working with Laravel collections. I have two collections:

    $dt = Carbon::now();
    $days = new Collection([]);

    /**
     * Create a calender month
     */
    for ($day = 1; $day <= $dt->daysInMonth; $day++) {
        $date = Carbon::create($dt->year, $dt->month, $day)->toDateString();
        $days->push(new Timesheet([
            'date' => $date,
        ]));
    }

    /**
     * Get all timesheets for user
     */
    $timesheets = Timesheet::where('user_id', $this->user->id)
        ->get();

\Illuminate\Database\Eloquent\Collection ($timesheets)

#attributes: array:5 [▼
    "id" => "1"
    "user_id" => "1"
    "date" => "2016-02-22 22:05:01"
    "created_at" => "2016-02-22 22:05:01"
    "updated_at" => "2016-02-22 22:05:01"
  ]
  // ... one or more ...

I have second collection giving me all days for a given month.

\Illuminate\Support\Collection ($days)

#attributes: array:1 [▼
    "date" => "2016-02-01 00:00:00"
]
// ... and the rest of the month.

I want to merge the $days collection with the $timesheet collection preserving the values of the $timesheet collection and removing any duplicates present in the $days collection. E. g. if $timesheets already contains '2016-02-24' I do not want to merge '2016-02-24' from $days. How do I do this?

like image 585
BusterX Avatar asked Feb 23 '16 20:02

BusterX


People also ask

How do I merge two laravel collections?

Laravel collection merge() method merge any given array to first collection array. If the first collection is indexed array, the second collection will be added to the end of the new collection. The merge() method can accept either an array or a Collection instance.

What is the use of pluck in laravel?

Laravel Pluck() is a Laravel Collections method used to extract certain values from the collection. You might often would want to extract certain data from the collection i.e Eloquent collection.

What is map function in laravel?

Laravel map() is a Laravel Collections method to pass callback function to each item in Collection. It is a easy yet powerful method to manipulate data in Laravel Collection. After operating on each item, map() method returns new Collection object with updated items.


1 Answers

Use merge:

$collection1 = Model1::all();
$collection2 = Model2::all();
$mergedCollection = $collection1->merge($collection2);

Documentation

The documentation talks about using it with arrays, but looking at the method signature it will take mixed arguments. Testing it on a local install of a Laravel 4 project worked for me.

like image 102
Jeff Lambert Avatar answered Oct 05 '22 05:10

Jeff Lambert