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

TuffRivers's avatar

Chaining Conditional Where Clause Laravel Query Builder

Hi All,

How can i chain this query together in laravel without using eloquent model, its based on input i get from user form, if the input exists, add it to where clause. I keep getting error "Syntax error, unexpecte ')"

right after the

'whereIn->('c.Client_Type', ['Inbound', 'Outbound']));
        $query = DB::table('Client_Inbound_Transactions as t')
        ->leftJoin('Client_Accounts as c','c.ClientID', 't.ClientID')
        ->select(
            'c.ClientID as ClientID',
            't.load_type AS LoadType'
            )
         ->whereIn('c.Client_Type', ['Inbound', 'Outbound']));
        if($loadType){
            $query = $query->where('load_type', $loadtType);
        }
        if($start_date){
            $query = $query =  $query->whereDate('t.Timestamp','>=',$start_date);
        }
        if($end_date){
            $query = $query->whereDate('t.Timestamp','<=', $end_date);
        }
  
   $date = $query->get();
0 likes
2 replies
MichalOravec's avatar
Level 75

Use conditional clauses instead of multiple if.

$data = DB::table('Client_Inbound_Transactions as t')
    ->leftJoin('Client_Accounts as c','c.ClientID', 't.ClientID')
    ->select('c.ClientID as ClientID', 't.load_type AS LoadType')
    ->whereIn('c.Client_Type', ['Inbound', 'Outbound'])
    ->when($loadType, function ($query, $loadType) {
        return $query->where('load_type', $loadtType);
    })->when($start_date, function ($query, $start_date) {
        return $query->whereDate('t.Timestamp', '>=', $start_date);
    })->when($end_date, function ($query, $end_date) {
        return $query->whereDate('t.Timestamp', '<=', $end_date);
    })->get();

https://laravel.com/docs/8.x/queries#conditional-clauses

And that error you have an extra parenthesis there.

It has to be like this

->whereIn('c.Client_Type', ['Inbound', 'Outbound']);

And not this one

->whereIn('c.Client_Type', ['Inbound', 'Outbound']));
                                                   ^ - here is the problem
1 like

Please or to participate in this conversation.