How To Make A Collection Of Two Models Grouped By Date In Laravel 5.5?

- 1 answer

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->string('name', 125);


        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.



I think your looking for the merge() method for merging two collection

        //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)