visulo
visulo

Reputation: 373

Laravel how sort merge collections

I have 3 query, my problem is I want the merged collection to be sorted by created_at.

How to merge and sort three query builder collections?

        $posts1 =\DB::table('posts')
        ->select('posts.*', 'users.nom','pratics.titre')
        ->join('pratics', 'posts.pratic_id','=','pratics.id')
        ->join('users', 'posts.user_id','=','users.id')
        ->where('pratics.user_id',$id)
        ->orderBy('posts.id', 'desc')
        ->get();

        $posts2 =\DB::table('posts')
        ->select('posts.*', 'users.nom','pratics.titre')
        ->join('journals', 'posts.pratic_id','=','journals.id')
        ->join('users', 'posts.user_id','=','users.id')
        ->where('journals.user_id',$id)
        ->orderBy('posts.id', 'desc')
        ->get();


        $posts3 =\DB::table('posts')
        ->select('posts.*', 'users.nom','pratics.titre')
        ->join('exos', 'posts.exo_id','=','exos.id')
        ->join('users', 'posts.user_id','=','users.id')
        ->where('exos.user_id',$id)
        ->orderBy('posts.id', 'desc')
        ->get();

$posts = array_merge($posts1,$posts2, $posts3)->sortby('created_at');

Upvotes: 1

Views: 1742

Answers (2)

LF-DevJourney
LF-DevJourney

Reputation: 28529

If you want to merge the collections, use merge() function like this:

$posts1->merge($posts2)->merge($posts3)->sortby('created_at');

And the array_merge() is not workable here. If you want to use array_merge(), you have to use toArray() before that.

Upvotes: 1

nibnut
nibnut

Reputation: 3127

I agree with @Vitalii Strimbanu that this is probably not the best way to get all your records.

That being said, to answer your question specifically, I believe the only thing you are missing is to make your merged array into a collection before you call sortby on it:

$posts = collect(array_merge($posts1,$posts2, $posts3))->sortby('created_at');

Hope this helps!

Upvotes: 1

Related Questions