Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent find returning null

I'm trying to retrieve a record from my database using Eloquents find method, however, it's unexpectedly returning null. If I run the query manually on the database then it returns the expected record.

I'm using the following in Laravel:

$support = Support::find(02155);

And the following directly on the database:

SELECT * FROM support WHERE id = 02155;

The primary key column is named 'id' with type smallint(5), unsigned and zerofill along with auto increment set. I based the above 'manual' query on the Laravel documentation according to what Laravel should be executing.

There aren't any errors reported (that I can see) and if I alter Eloquent method to 'all' then all of the records are correctly returned.

like image 725
Jake Stubbs Avatar asked Mar 10 '13 18:03

Jake Stubbs


1 Answers

This is caused because numbers starting with 0 are considered an octal by PHP, as per: http://php.net/manual/en/language.types.integer.php

It seems that PHP converts the number to a decimal before executing the MySQL query which means the query is formed with an incorrect number.

For example:

Support::find(02155);

Becomes:

'SELECT * FROM mytable WHERE id = 1133'

The Solution

I resolved this by typecasting the number to an integer using (int) before I used it with Eloquents find method. It will also work if you pass the number as a string (i.e. in quotes), like so:

Support::find('02155');
like image 196
Jake Stubbs Avatar answered Sep 22 '22 10:09

Jake Stubbs