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

Ligonsker's avatar

Can I join with a query builder instance?

I have a query builder statement:

$builder = DB::table('my_table')->where(...)->where(...)->orderBy(...)->orderBy(...)

but without the get() at the end. Then I wanted to join the result that would outcome from this query:

$data = $builder->join('second_table'), function($join){
    $join->on('my_table.id' = 'second_table.my_table_id')->where(...);
})->get();

But that doesn't work, it also returns an instance of Illuminate\Database\Query\Builder

Is it possible to do what I'm trying to do?

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

That should work, but you have a syntax error here (= should be a string)

$join->on('my_table.id', '=', 'second_table.my_table_id')

So to be clear, $data will be the result of the query, not $builder

1 like
Ligonsker's avatar

@tykus Thank you, I manually copied the code and in reality it's like you wrote, I accidentally dd()'d the wrong variable 😅

Please or to participate in this conversation.