Peter Estiven
Peter Estiven

Reputation: 424

Laravel Eloquent model returns value even with a wrong condition

I don't get the following problem :

  1. $user = App\User::where('id', 1)->first(); works

  2. $user = App\User::where('id', '1')->first(); works - same result

  3. $user = App\User::where('id', '1xxxx')->first(); works - same result

  4. $user = App\User::where('id', 'x1')->first(); doesn't work

I'm surprised by 2., more by 3. and even more by 4.. Any clue ?

Upvotes: 1

Views: 722

Answers (2)

Prafulla Kumar Sahu
Prafulla Kumar Sahu

Reputation: 9693

As id column is type of int, it is expecting an int value for compare and (int)'1xxxx' = 1 , so all these results are expected only.

using tinker

>>> App\User::where('id', '1xxxxx')->first();
=> App\User {#3118
     id: 1,
     name: "superadmin",
     email: "[email protected]",
     created_at: "2019-01-11 19:06:23",
     updated_at: "2019-01-11 19:06:23",
   }
>>> App\User::find('1xxxxx');
=> App\User {#3123
     id: 1,
     name: "superadmin",
     email: "[email protected]",
     created_at: "2019-01-11 19:06:23",
     updated_at: "2019-01-11 19:06:23",
   }

and

    >>> App\User::find('xxxxx1');
    => null
   Psy Shell v0.9.9 (PHP 7.2.10 — cli) by Justin Hileman
   >>> App\User::where('id', 'xxxxx1')->first();
   => null
   >>> App\User::where('id', 'x1')->first();
   => null
    >>>
   >>> App\User::find('x1');
   => null
    >>>

Upvotes: 3

abr
abr

Reputation: 2129

It happens because, in background, it matches the value based on the column type.

Being the column an int, it casts the value into an int form, such as this

https://3v4l.org/JkU9H

Meaning all 3 points match value 1, while the last one matches 0 due to being unable to convert "x" into a int

Upvotes: 1

Related Questions