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

mikebolingbroke's avatar

Include Null on when conditions

Hi,

Having spent hours on this and not getting any further, really need some advice.

I have three dropdowns; product_class, product_type, product_variety. Each one triggers a axios (vue) request that is hooked up to the below function. (The below function works fine) What i need to do is include any null values that exist within the tables. I have tried whereNull within the when condition (where it needs to be) but it returns no data.

public function sources(Request $request) {

    $p_classesId = $request->input('p_class');
    $p_typesId = $request->input('p_type');
    $p_varietyId = $request->input('p_variety');

    $locationData = LocationsStores::with("location")
        ->where("product_class_id",$p_classesId)
        ->when($p_typesId, function ($query, $p_typesId) {
            return $query->where("product_type_id", $p_typesId);
        })
        ->when($p_varietyId, function ($query, $p_varietyId) {
            return $query->where("product_variety_id", $p_varietyId);
        })
        ->get();

    return response()->json(["sources" => $locationData ]);

}

Really appreciate help on this.

Thanks Mike

0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

There is an orWhereNull Builder method which you can chain onto the query:

$locationData = LocationsStores::with("location")
	->when($p_typesId, function ($query, $p_typesId) {
           	$query->where(function ($q) {
			$q->where("product_type_id", $p_typesId)
				->orWhereNull('product_type_id');
		});
        })
	->get();

Just be sure that the resulting query is properly nesting the OR part

tykus's avatar

No worries, please mark the Best Reply above.

Please or to participate in this conversation.