3

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 ?

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

1

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();

2 Comments

this might be a solution too, but that doesn't work in my case. I join tables. Also there's a syntax error out there like 'firstField', '$var1' should be 'firstField', '=', $var1 but thank you for giving me ideas anyway.
Well in your question there is no join... And I don't see why this shouldn't work with joins. Also = can be omitted
1

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();

5 Comments

Can you provide some explanation?
blankBird_ said its code doesn't work if those vars are null. Its means that you can check it, and if it are null you can find in table 0 or, for example 'null'.
Maybe it would be helpful to explain the ternary logic you're using, some people may be unfamiliar with it.
Ok, its like simple 'if-else', but in srort form. Syntax is simple: echo (condition == 0) ? "do something if true" : "do somsing if false";
You can edit your answer to elaborate or make it clearer. No need to restrict yourself to comments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.