Skip to content
Advertisement

How can we use when clause for multiple tables in laravel eloquent query?

I’m using condition based queries but i have a problem how can i use (when) with other table/model because i have to put condition based on the other table column (branch_id).

branch_id comes from steps table.

               ContactBoard::with(['steps'])
                ->when($request->has('branch'), function ($query) use ($request) {
                    $query->where('steps.branch_id', $request->query('branch'));
                })
                ->where('id', $board_id)->get()->first();

Advertisement

Answer

You can make it like

$query->when($request->has('branch'), function ($q)use($request) {
    return $q->with('steps',function($q){
            $q->where('branch_id', $request->query('branch'));
        });
  });
$query = $query->get();
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement