6 months ago

merge 2 collections

Posted 6 months ago by pmusa


Is there a method to merge 2 collections? I could not find any

Here is collection #1 : Here is collection #2 :

I'd like to merge those 2 collections based on "user_id" of collection #1 and "id" of collection #2. I'd like to call the key "user", so that in the end I can reach a comment's author like this:

foreach ($comments as $comment)
    echo 'Author is ' . $comment->user->name;

In case you wonder what's in my controller, here it is:

        $post = Post::with('user', 'comments')
        $comments = $post->comments;
        $users = User::findMany($comments->pluck('user_id')->toArray());

Basically what I want to achieve is to build a big fat collection then send it to the view all ready to be read. I'm not super happy with how Laravel fires SQL requests (n+1 problem). Eager-loading helped retrieving the user infos of the post's author, but it fires a SELECT for every single comment author ("user_id" within parent "comments" of collection #2)...

Thank you

Please sign in or create an account to participate in this conversation.