Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

carlosmtns's avatar

Laravel querying

Hello all, Is it possible to use query results to join on a second query?

example, first query:

$threads = DB::table('threads')

        (many joins....)

        -> select('threads.id', 'threads.user_id','users.name as user_name', 'users.avatar as user_avatar'.........)
        -> groupBy('threads.id')
        -> OrderBy('threads.created_at', 'asc')
        -> get();

and use that results to filter a second query like:

$messages = DB::table('messages')
        -> join($threads, $threads.id, '=', 'messages.thread_id')
        -> select('messages.sender_id', 'messages.message')
        -> get();

Thanks in advance for any help

0 likes
2 replies
r3b00t's avatar
r3b00t
Best Answer
Level 1

I don't think that's possible, what do you want to accomplish? Do you want to get all threads with its messages? then you can join the second query to the first one.

If you want to take the messages from one or some threads, you can use pluck method to get the thread ids from $threads Collection, convert it to array and use where or whereIn in the second query.

$threadIds = $threads->pluck('id')->toArray();

in the second query just add:

->whereIn('thread_id', $threadIds)
carlosmtns's avatar

Yes, get all messages from 1 or more threads. Its working ! Thanks for your suggestion ;)

Please or to participate in this conversation.