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

milanpatel's avatar

How to Add IF ELSE Condition Between Laravel Query

I Want To Add if Else Condtion Between Query. If Distance is Not Equal To 0 Then Execute Query With Having Condition......... Else Remove Having Conition

I Want Like This. As Shown Below. But Got Error. Please Suggest Me How Can I do This ? Below Code Is Not Working.

        $data = DB::table('tbl_jobs')
                ->select(array("*",
                    DB::raw("(6371 * acos(cos(radians($location->latitude)) * cos(radians(users.latitude)) * cos(radians(users.longitude) - radians($location->longitude)) + sin(radians($location->latitude)) * sin(radians(users.latitude))))as distance"),
                    DB::raw("IFNULL((select CASE WHEN id IS NULL THEN 0 ELSE 1 END from tbl_users_apply_job where user_id = $user_id and job_id = tbl_jobs.job_id),0)as applied_by_me"))
                )
                ->join('users', 'tbl_jobs.job_added_by', '=', 'users.id')
                ->join('tbl_company', 'users.id', '=', 'tbl_company.company_owner_id')
		if($distance != "0"){
                   $data->having("distance", "<=", $distance);
		}
                ->get();
0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

Use the when Builder method:

// ...
->join('tbl_company', 'users.id', '=', 'tbl_company.company_owner_id')
->when($distance != "0", function ($builder) use ($distance)
	$builder->having("distance", "<=", $distance);
})
->get();

When the condition is satisfied, the Closure will be executed (this method also takes a third argument (also a Closure) for the else part when the condition is not satisfied)

1 like
tykus's avatar

No worries @milanpatel, please consider marking the Best Reply above if your issue has been solved.

Please or to participate in this conversation.