Search code examples
phplaravelcollectionsmerging-data

How to merge two collections in Laravel?


I get the data from $request object the I convert it into collection:

foreach ($request->get('dates') as $date) {
    $this->inputDates->push([
        "starttime" => $this->convert($date['starttime']),
        "endtime" => $this->convert($date['endtime'])
    ]);
}

The I fetch data from database table:

$this->existDates = $this->get($this->user->getId())->map(fn($model) => $model->only(['starttime', 'endtime']));

After all I try to merge two collectons:

$this->allDates = $this->existDates->merge($this->inputDates);

As result I got this error:

{ "message": "Call to a member function getKey() on array", "exception": "Error", "file": "C:\xampp\htdocs\app\laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Collection.php", "line": 343, "trace":

I expect to get merged collection with two fields: starttime, endtime. Then reduce it into flat array: [date1, date2, date3...] and sort it.


Solution

  • You can merge by doing array and object conversions:
    Push to array:

    $this->inputDates = (object) array_push((array) $this->inputDates, array(
        "starttime" => $this->convert($date['starttime']),
        "endtime" => $this->convert($date['endtime'])
    ));
    

    Merge arrays:

    $this->allDates = (object) array_merge($this->existDates->toArray(), $this->inputDates->toArray());