Laravel Eloquent will find return null

I am trying to get a record from my database using the Eloquents search method, however it unexpectedly returns null. If I run the query manually in the database, it returns the expected record.

I use the following in Laravel:

$support = Support::find(02155); 

And the following are directly in the database:

 SELECT * FROM support WHERE id = 02155; 

The primary key column has the name 'id' of type smallint (5), unsigned and zerofill along with the auto increment set. I based the above β€œmanual” query in the Laravel documentation according to what Laravel should do.

There are no error messages (what I see), and if I changed the Eloquent method to β€œall,” then all records will be returned correctly.

+4
php mysql eloquent laravel
source share
1 answer

This is because numbers starting with 0 are considered octal in PHP, according to: http://php.net/manual/en/language.types.integer.php

PHP seems to convert the number to decimal before executing a MySQL query, which means the query is formed with the wrong number.

For example:

 Support::find(02155); 

becomes:

 'SELECT * FROM mytable WHERE id = 1133' 

Decision

I solved this by pointing the number to an integer using (int) before using it with the Eloquents search method. It will also work if you pass the number as a string (i.e. in quotation marks), for example:

 Support::find('02155'); 
+14
source share

All Articles