Laravel Eloquent model id as string return wrong value in
This is because by default the primary key is casted as int
unless explicitly stated otherwise.
(int) "wISw4JmlMQCCrMupjojcuDTK3k4hwtkb" == 0
The value still exists as string, but if you use the $model->id
it will go through magic __get()
method defined in Illuminate\Database\Eloquent\Model
class.
I'm not going to argue against using id
field as string, but if you do and also want to get the string value using $model->id, you'll have to cast it as string in you model definition. There is a protected $casts array you can use for that. Just add the following to your OauthClient model:
protected $casts = ['id' => 'string'];
This will do the trick and cast the id attribute as string instead of default integer. All though I would reccommend not to use id as string in the first place.
Update:
There is also an $incrementing
property, which you can set to false
on your models, to tell Laravel you want non-incrementing or non-numeric primary key. Set it on your models like this:
public $incrementing = false;
Update 2:
Information about this is now also added to official documentation. Look for Primary Keys section at Eloquent docs:
In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that by default the primary key will be cast to an int automatically. If you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false. If your primary key is not an integer, you should set the protected $keyType property on your model to string.
Setting public $incrementing = false;
worked for me.
http://www.laravel.io/forum/12-14-2015-id-as-string