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

moses's avatar
Level 2

How to add a additional condition in a join using query builder laravel 5.3?

My regular query is like this :

SELECT e.field1, b.field2, c.field3, d.field4, a.field5 , a.field6 
FROM table1 a
LEFT JOIN table2 b ON a.field2=b.field2
LEFT JOIN table3 c ON a.field2=c.field2 AND a.field3=c.field3
WHERE a.field6 LIKE '%bintara%' OR b.field2 LIKE '%bintara%' OR b.field7 LIKE '%bintara%'
ORDER BY e.field1, b.field2, c.field3, a.field5

I change to query builder like this :

$test = DB::table('table1 AS a')
        ->leftJoin('table2 AS b', 'a.field2', '=', 'b.field2')
        ->leftJoin('table3 AS c', function($join){
            $join->on('a.field2', '=', 'c.field2');
            $join->on(DB::raw('a.field3 = c.field3'), DB::raw(''), DB::raw(''));
        })
        ->select('e.field1', 'b.field2', 'c.field3', 'd.field4', 'a.field5', 'a.field6')
        ->where('a.field6', 'LIKE', '%$bintara%')
        ->orWhere('b.field2', 'LIKE', '%$bintara%')
        ->orderBy('e.field1', 'ASC')
        ->orderBy('b.field2', 'ASC')
        ->orderBy('c.field3', 'ASC')
        ->orderBy('ca.field5', 'ASC')
        ->get();

Is that true?

0 likes
12 replies
Gog0's avatar

What are the DB:raw() functions for in your case?

I never tried joins with multiple conditions but my feeling is that it should be nested on conditions in the closure:

->leftJoin('table3 AS c', function($join){
    $join->on('a.field2', '=', 'c.field2')
         ->on('a.field3', '=', 'c.field3');
})
5 likes
moses's avatar
Level 2

I you try?

It's not working

Gog0's avatar

@moses no I didn't as I don't have database to test this right now, but what "not working" means?

moses's avatar
Level 2

LEFT JOIN table3 AS c ON a.field2 = c.field2 AND a.field3= c.field3 = ``

Should this : LEFT JOIN table3 AS c ON a.field2 = c.field2 AND a.field3= c.field3

moses's avatar
Level 2

Its what you gave me

->leftJoin('table3 AS c', function($join){ $join->on('a.field2', '=', 'c.field2') ->on('a.field3', '=', 'c.field3'); })

The result : LEFT JOIN table3 AS c ON a.field2 = c.field2 AND a.field3= c.field3 = ``

you might as well just try it

arjunRamkumar's avatar

You can simply add multiple conditions by adding them as where() inside the join closure


->leftJoin('table3 AS c', function($join){
        $join->on('a.field2', '=', 'c.field2')
        ->where('a.field2', '=', true)
        ->where('a.field3', '=', 'c.field3');
})
4 likes
yasha's avatar

@wilpat That where join syntax might be wrong, since on joins fields and where joins conditions.

That last where join will join column a.field3 with string value c.field3, maybe check the ->toSql() return on that builder.

2 likes

Please or to participate in this conversation.