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

lat4732's avatar
Level 12

exists() query condition in left join

Hello. I'm having a query that is based on GET parameters. In short, if some parameters (checkboxes) are set the query is changing. But now I need a little bit different structure for one of the checkboxes. When checked - I need to check if there is an existing row with a specific matching column (detail_id) value from another table. I tried with:

		$upgrading->leftJoin('anotherTable', function($join) {
                $join->on('table.id', '=', 'anotheTable.detail_id')->exists();
         });

The structure of the query is:

			$upgrading = Table::query();
			if(!empty($request->someGetParam)) {
					..............
			}
			if(!empty($request->someGetParam)) {
					..............
			}
			if(!empty($request->someGetParam)) {
			   $upgrading->leftJoin('anotherTable', function($join) {
                   $join->on('table.id', '=', 'anotheTable.detail_id')->exists();
               });
			}
			$upgradingFinal = $upgrading->where(....)->paginate(20);

Any idea?

0 likes
4 replies
Snapey's avatar

the ->exists() terminates and executes the query

You should perform the join AND add a where query for the related record.

lat4732's avatar
Level 12

@Snapey

if(!empty($request->someGetParam)) {
$upgrading->join('anotherTable', 'anotherTable.detail_id', '=', 'table.id');
$upgrading->where('anotherTable.detail_id', '=', 'table.id');
});

?

Snapey's avatar

btw, this is a bit more elegant

if($request->has('someGetParam')) {
1 like

Please or to participate in this conversation.