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.
<?phpnamespace App;
use Illuminate\Database\Eloquent\Model;
class Test extends Model
{
protected $primaryKey='pkey';
protected $table = "test_laravel";
public $timestamps = false;
protected $fillable = ['pkey'];
}
<?phpnamespace 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::get('/get-test-data','TestController@getDataFromDb');CREATE TABLE test_laravel (pkey varchar(50) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;INSERT INTOtest_laravel(pkey) VALUES
('100512242651368060'),
('100512242651368564');
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
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