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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With