Vishal Vaishnav
Vishal Vaishnav

Reputation: 3422

How to write if elseif else condition laravel query builder?

Below is my query,

rows = "SELECT * FROM `table` WHERE score = 1"
if (rows.Count < 3) //at least one row
return if;
else if(rows.Count >7)
return 'else if';
else
return 'else';

How to write above query with when using querybuilder laravel. Actually I want to know about how to write else condition.

Below is my code;

$query=DB::table('aaa')
->select('*')
->when($count<3,function ($q){
    echo 'if';
})
->when($count>7,function ($q){
    echo 'else if';
})

///I dont know how to write else condition here

Upvotes: 4

Views: 17350

Answers (3)

Sam Prasanna
Sam Prasanna

Reputation: 141

$role = $request->input('role');
 
$users = DB::table('users')
             ->when($role, function ($query) use ($role) {
                return $query->where('role_id', $role);
             })
             ->get();

Upvotes: 0

Qirel
Qirel

Reputation: 26450

There's no else counterpart to when() when using multiple conditions (if/elseif/else), but if you think of it, it's just the inverse of the sum of the other conditions. To exactly mirror a PHP if/elseif/else, you need to check the first condition, and then explicitly check the second condition and not the first condition, and to mimic the else condition, its just whichever boolean condition is needed when all else conditions fails.

$query = DB::table('table')
           ->select('*')
           ->when($count < 3, function ($q) {
               // if count < 3
           })
           ->when($count > 7, function ($q) {
               // else if count > 7
           })
           ->when($count =< 7 && $count >= 3, function($q) {
               // Else, count between 3 and 7 (inclusive)
           });

You can conditionally apply a where clause "manually" by using native PHP if/elseif/else controls and apply a simple where(), which might be more explicit if your conditions become very expressive or complex.

There is however an else condition when you have a simple if/else, as you can provide it another closure. This cannot be used with multiple conditions, as you've originally asked about, but I included it for reference.

$query = DB::table('table')
           ->select('*')
           ->when($count < 3, function ($q) {
               // if count < 3
           }, function($q) {
               // Else, count greater or equal to 3
           });

Upvotes: 12

STA
STA

Reputation: 34678

May be this is what you are seeking for :

$query=DB::table('aaa');

if($count < 3) {
    $query->where('quantity', '>=',  $count);
}
 
if($count < 7) {
    $query->where('quantity', '>', $count);
}

$query = $query->get();

Upvotes: 3

Related Questions