How To Make A Collection Of Two Models Grouped By Date In Laravel 5.5?
I have two models Tour
and Adventure
. I want to make a group of both tours and adventures grouped by date. And display it like this:
July 17
Tour 1 Tour 2 Tour 3 Adventure 1 Adventure 2 Adventure 3
July 16
Tour 1 Tour 2 Tour 3 Adventure 1 Adventure 2 Adventure 3
I know how to make the grouping of a single model. It goes like this:
Tour::orderBy('created_at', 'desc')->take(20)->get()->groupBy(function($item)
{
return $item->created_at->format('d-M-y');
});
How can I join the two models and display them into a single date? With the current code day appear in different collections.
EDIT: Including the table migrations.
public function up()
{
Schema::create('tours', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 125);
$table->string('slug')->index();
$table->text('description')->nullable();
$table->string('duration')->nullable();
$table->string('url')->nullable();
$table->boolean('ended')->default(false)->index();
$table->timestamps();
});
DB::statement('ALTER TABLE tours ADD FULLTEXT search(name)');
}
The migration for the adventure model is the same as the tour. The two models does not share a relationship between them.
Answer
I think your looking for the merge() method for merging two collection laravel.com/docs/5.8/collections#method-merge
//Get all Tours
$tours= Tour::orderBy('created_at', 'desc')->get();
//Get all adventures
$adventures= Adventure::orderBy('created_at', 'desc')->get();
//Merge both collection into 1 single collection and group according the date
$dates= $tours->merge($adventures)->groupBy(function($item) {
return $item->created_at->format('d-M-y');
});
return view('someView', compact('dates'));
And then you can loop within the date
@foreach($dates as $date => $activity)
<h2>{{$date}}</h2>
<li>
{{$activity}}
</li>
@endforeach
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS - Conditionally Load a Different Page
- → Make a Laravel collection into angular array (octobercms)
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
- → Validating fileupload(image Dimensions) in Backend Octobercms
- → OctoberCMS Fileupload completely destroys my backend
- → How do I call the value from another backed page form and use it on a component in OctoberCms