Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jc_anchor's avatar

Conditional statements in query builder

I have been using documentation successfully with when statements described here: https://www.laravel.com/docs/5.2/queries#conditional-statements

I have four conditional statements like this one in my model which have all been working:

          ->when($qData['zip'], function ($query2) use ($qData) {
              $query2->where('rentals.zip', '=', $qData['zip']);
          })

On Thu, Jun 9 I added a new service called Entrust by Zizaco to handle user permissions. I updated Laravel after adding the new service in my composer.json file. Now I am getting this error message on my conditional statements:

FatalErrorException in Rental.php line 101: Call to a member function when() on null

If all four of my select variables are empty, the query still works. If any one of the variables which are zip, beds, min and max are selected, the error message above appears.

The new service mentioned above is not used at all in the query. The only change is now I am running Laravel /Frameword v5.2.37

I am stumped as to why this stopped working. Documentation says when condition does not execute if the first statement is false.

0 likes
4 replies
d3xt3r's avatar

Documentation says when condition does not execute if the first statement is false.

Nopes , it says

The when method only executes the given Closure when the first parameter is true. If the first parameter is false, the Closure will not be executed.

Your error says Call to a member function when() on null. i.e. if you are using something like $rental->when(...) the value of $rental is null

jc_anchor's avatar

I did some checking with data dump on all the variables for the query. They are all there. I decided to revert back to the version of Laravel Framework v5.2.32 that was working in my development. The conditional statements began working again!

Then I updated to the most current version as of today which is Laravel Framework v5.2.38 and they stopped working again. I have reported the problem to Taylor with documentation. I am staying at v5.2.32 for now.

jc_anchor's avatar

I tested further to find out what build caused the break in functionality with conditional statement in query builder. Laravel Framework v5.2.33 works and v5.2.34 produced the error message I have been having. I will evaluate the difference and see if I can pin point where the problem is coming from.

jc_anchor's avatar
jc_anchor
OP
Best Answer
Level 3

@themsaid saw my problem and noted the following:

you need to use return inside the callback

when($qData['zip'], function ($query2) use ($qData) {
    return $query2->where('rentals.zip', '=', $qData['zip']);
})

This solved my problem, I was able to update to current version of Laravel Framework and everything is working correctly!

1 like

Please or to participate in this conversation.