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

pravash's avatar

laravel conditional nested query

I have a table name product having column name taraget_university. I need query somethings like

Product::where("sold_to_user",null)

if target_university == null then continue

if target_university !=null then query->where("target_university",$university -> id) ======================================= ->whereIn("user_id",$userArray) ->get();

How to add those conditional query ??

0 likes
3 replies
ouhare's avatar
ouhare
Best Answer
Level 24
$p = Product::whereNull("sold_to_user")
    ->where(function ($q) use ($university) {
        $q  ->whereNull("target_university")
            ->orWhere("target_university", $university->id);
    })->whereIn("user_id", $userArray)->get();
developre's avatar

Ouhare, you should use whereNotNull. PRAVASH needs the query for target_university !=null ( $q ->whereNull("target_university"))

Please or to participate in this conversation.