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

Stallyons Tester's avatar

WhereHas adding where Null condition in query

$data = Schedule::whereHas('bus.cargos',function($query) use($request){
                            $query->where('cargo_type_id',$request->cargo_type);
                        })
                        ->toSql();

 dd($data);

it gives this query

select * from `schedules` where exists (select * from `buses` where `schedules`.`bus_id` = `buses`.`id` and exists (select * from `cargo_types` inner join `bus_cargo_type` on `cargo_types`.`id` = `bus_cargo_type`.`cargo_type_id` where `buses`.`id` = `bus_cargo_type`.`bus_id` and `cargo_type_id` is null))

but i want query without "and cargo_type_id is null "

0 likes
2 replies
sirch's avatar
sirch
Best Answer
Level 27

dd $request->cargo_type check if it has a value

Stallyons Tester's avatar

@sirch Thanks. there was issue with key cargo_type. Actually the name is cargo. Thanks for assistance

Please or to participate in this conversation.