Framework: Elequent wrongly interperting long numbers

Created on 27 Feb 2018  路  2Comments  路  Source: laravel/framework

  • Laravel Version: 5.5.x
  • PHP Version: 7.0.13
  • Database Driver & Version: Mysql 5.7.16

Description:

A long number i,e of 18 digit is saved in database, but whenever the data is accessed through laravel eloquent it gives wrong number i,e of 10 digits.
Eg. For the number 100512242651368060, eloquent model gives 2147483647 which is wrong while query builder gives 100512242651368060 which is correct.

Steps To Reproduce:

  • Model Code
    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Test extends Model
{
protected $primaryKey='pkey';
protected $table = "test_laravel";
public $timestamps = false;
protected $fillable = ['pkey'];
}

  • Controller Code
    <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Test;
use DB;
class TestController extends Controller
{
public function getDataFromDb(){
$data = Test::all()[0]->pkey;
$data1 = DB::table('test_laravel')->get()[0]->pkey;
return "Same data from Elequont ".$data." & Query Builder ".$data1;
}
}

  • Route Code:(web.php)
    Route::get('/get-test-data','TestController@getDataFromDb');
  • Database Table
    CREATE TABLE test_laravel (
    pkey varchar(50) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTOtest_laravel(pkey) VALUES
('100512242651368060'),
('100512242651368564');

  • Result
    Same data from Elequont 2147483647 & Query Builder 100512242651368060

Most helpful comment

This is due to PHP's maximum integer size. To get round this you can avoid casting the primary key to an integer by setting protected $keyType = 'string'; on your model

All 2 comments

This is due to PHP's maximum integer size. To get round this you can avoid casting the primary key to an integer by setting protected $keyType = 'string'; on your model

Thanks for the solution! @ntzm

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ghost picture ghost  路  3Comments

JamborJan picture JamborJan  路  3Comments

Fuzzyma picture Fuzzyma  路  3Comments

digirew picture digirew  路  3Comments

PhiloNL picture PhiloNL  路  3Comments