Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 459
Vishal Vaishnav Avatar asked Oct 21 '25 11:10

Vishal Vaishnav


1 Answers

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
           });
like image 100
Qirel Avatar answered Oct 23 '25 02:10

Qirel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!