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();
// ...
->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)