saimcan
saimcan

Reputation: 1762

Laravel query building with variables

Assume that i have variables like $var1 and $var2.

Assume that i want to have a query like

$myQuery = DB::table('myTable')
           ->where('firstField', '=', $var1)
           ->where('secondField', '=', $var2)
           ->get();

Of course this one doesn't work when my variables are null. I want to control them, and do something if they are null.

I should create a query based on those variables and filter them with the values they hold.

Any other ideas how to do this ?

Upvotes: 3

Views: 6895

Answers (3)

ffsantos92
ffsantos92

Reputation: 366

Here's a solution:

$results = DB::table('myTable')->where(function($query) use ($var1, $var2) {
               if ( ! empty($var1)) {
                   $query->where('firstField', '=', $var1);
               }
               if ( ! empty($var2)) {
                   $query->where('secondField', '=', $var2);
               }
           })->get();

Edit: Corrected ::where to ->where

Upvotes: 6

Mario
Mario

Reputation: 197

For example you can make like this:

$myQuery = DB::table('myTable')
       ->where('firstField', '=', is_null($var1)?0:$var1)
       ->where('secondField', '=', is_null($var2)?0:$var2)
       ->get();

Upvotes: 1

lukasgeiter
lukasgeiter

Reputation: 152890

Not sure this is what you want but you can easily build a query in multiple "steps" using conditionals:

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

if($var1 !== null){
    $query->where('firstField', $var1);
}
if($var2 !== null){
    $query->where('secondField', $var2);
}

$result = $query->get();

Upvotes: 1

Related Questions