Reputation: 782
hi how can we implement a condition checks in laravel query builder
$flag_email =true;
$query = DB::table('customer');
if($flag_email) {
$query->where('email','=',$email);
}
if(!$flag_email) {
$query->where('mobile','=',$email);
}
$query->get();
Upvotes: 1
Views: 464
Reputation: 15529
Ternary operator to the rescue:
$query = DB::table('customer')->where($flag_email?'email':'mobile',$email);
Upvotes: 1
Reputation: 15115
use when
method here to check condition see
$query = DB::table('customer')
->when($flag_email, function ($query,$email) {
return $query->where('email', $email);
})
->when(!$flag_email, function ($query,$email) {
return $query->where('mobile', $email);
})->get();
Upvotes: 3
Reputation: 211
you can use ->when
to do conditional check
$query = DB::table('customer')
->when($flag_email, function ($query, $email) {
return $query->where('email', $email);
})
->when(!$flag_email, function ($query, $email) {
return $query->where('mobile', $email);
})->get();
Upvotes: 2
Reputation: 934
You can try by this way. This way will outputs your desire one. This just a way, I am not sure, this one is the proper way.
$flag_email =true;
$query = DB::table('customer');
if($flag_email)
$query = $query->where('email','=',$email);
if(!$flag_email)
$query = $query->where('mobile','=',$email);
$result= $query->get();
Upvotes: -1