4

Inside a model class of Laravel 5 I came across the following code which I am not sure what it means.

$query = User::query();

\Request::input('name') and $query->where('name', 'like', '%' . \Request::input('name') . '%');
\Request::input('email') and $query->where('email', 'like', '%' . \Request::input('email') . '%');

return $query->paginate(15);

Is it the same as the following code?

if (\Request::input('name')) {
    $query->where('name', 'like', '%' . \Request::input('name') . '%');
}

if (\Request::input('email')) {
    $query->where('email', 'like', '%' . \Request::input('email') . '%');
}
Troyer
  • 6,765
  • 3
  • 34
  • 62
O Connor
  • 4,236
  • 15
  • 50
  • 91
  • 4
    _"Is it the same as the following code?"_ Yes and the latter is more readable. The former is using short-circuit evaluation – Phil May 08 '18 at 06:58
  • Yes............ – Duc Filan May 08 '18 at 06:58
  • 2
    IMHO the first example is just bad style and should not be used. – Nigel Ren May 08 '18 at 06:58
  • @Phil This question is not a real duplicate of the linked question, as it more belongs to `if` statements. I know what you mean, but this is confusing for newbies ... – eisbehr May 08 '18 at 07:02
  • @eisbehr it doesn't have to be exactly the same. There's examples in the answers on that question that answer this one. It also links to articles on short-circuit evaluation. – Phil May 08 '18 at 07:05
  • 1
    There's a lot of online code in tutorials that does things like `mysqli_connect... or die()` the principle is the same. `or` and `and` are basically the same as `||` and `&&` but just have a different precedence (which in your example doesn't even come into play) – apokryfos May 08 '18 at 07:28
  • I agree -- this question is closely related to [Does PHP have short-circuit evaluation](https://stackoverflow.com/questions/5694733/does-php-have-short-circuit-evaluation?noredirect=1&lq=1), but there's enough difference for it not to be a duplicate. – lonesomeday May 08 '18 at 07:43
  • To address the question in the title, "X and Y" is **not** the same as "true". – Álvaro González May 08 '18 at 08:08

1 Answers1

3

It's short-circuit evaluation. The PHP && and and operators are the same for the most part (except for precedence, which we can ignore here). All boolean operators work with short-circuit evaluation; i.e. 0 and 1 can never be true because 0 is falsey, so PHP doesn't even need to evaluate the second operand 1. Pretty much all languages do this.

Here this is used as a shorthand if. If \Request::input('name') is truthy, the second operand $query->... will be evaluated, otherwise it'll be skipped.

This is stylistically questionable and hardly endorsed, not least because it spawns questions like this. You should just write a traditional if, it's easier to comprehend and there's no shortage of lines you need to preserve.

deceze
  • 510,633
  • 85
  • 743
  • 889