Anoop P S
Anoop P S

Reputation: 782

How can i create a conditional check in laravel query

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

Answers (4)

Amarnasan
Amarnasan

Reputation: 15529

Ternary operator to the rescue:

$query = DB::table('customer')->where($flag_email?'email':'mobile',$email);

Upvotes: 1

Jignesh Joisar
Jignesh Joisar

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

MekjkrhG
MekjkrhG

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

tohasanali
tohasanali

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

Related Questions