landry moutongo
landry moutongo

Reputation: 134

Order three different and unrelated models in laravel

I have three different models and I want to filter them and return them in the same object by creation date. The problem is that the filter must be applied on all models at once and not on each model successively.here are my three models, I don't know how to continue, need help

$quick = Model::with('user')->orderByDesc('id')->get();
$simple = Models::with('user')->orderByDesc('id')->get();
$suivi = Modelss::with(['user', 'position'])->orderByDesc('id')->get();

Upvotes: 0

Views: 68

Answers (1)

Hesan Naveed
Hesan Naveed

Reputation: 251

If there is no link in between the models and you want to retrieve data by ordering them all together. You need to use Collections for this.

What you can do after your 3 line of code is:

$quickSimpleMerged = $quick->merge($simple);
$merged = $quickSimpleMerged->merge($suivi);

$result = $merged->all();

Now that you have 1 collection including all data from 3 models of yours, you can simply run:

$result->sortByDesc('created_at');

Upvotes: 2

Related Questions