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

rafaelg21's avatar

Query Builder DB:: sentencia IF

Good afternoon friends, I have a problem I want to make an if statement within a Query Builder to avoid having to do reworked queries.

This is what I want to do but it gives me error.

 $history=DB::table('history_inventory as H')
            ->join('products as P','H.idproduct','=','P.id') 
            ->join('actions as A','H.action','=','A.id')  
            if(isset($idzone) && $idzone!=0){
              ->join('status_general as S','P.status','=','S.id') 
            }
            ->join('zones as Z','H.idzone','=','Z.id')       
            ->paginate(20);

ERROR: syntax error, unexpected 'if' (T_IF)

The problem there is for him; Before the if but if I put it it will not execute the other calls where. What can I do to concatenate the QUERY?

0 likes
2 replies
papa's avatar
papa
Best Answer
Level 3

Try something like this

$history = DB::table('history_inventory as H')
    ->join('products as P','H.idproduct','=','P.id') 
    ->join('actions as A','H.action','=','A.id');

if(isset($idzone) && $idzone!=0){
    $history->join('status_general as S','P.status','=','S.id');
}

$history->join('zones as Z','H.idzone','=','Z.id')->paginate(20);
1 like
rafaelg21's avatar

Thank you very much for your help @papa . Excellent contribution friend. I worked well. Solved

Please or to participate in this conversation.