Laravel 5.2 – Use a String as a Custom Primary Key for Eloquent Table becomes 0

This was added to the upgrade documentation on Dec 29, 2015, so if you upgraded before then you probably missed it.

When fetching any attribute from the model it checks if that column should be cast as an integer, string, etc.

By default, for auto-incrementing tables, the ID is assumed to be an integer in this method:

https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L2790

So the solution is:

class UserVerification extends Model
{
    // if your key name is not 'id'
    // you can also set this to null if you don't have a primary key
    protected $primaryKey = 'your_key_name';

    public $incrementing = false;

    // In Laravel 6.0+ make sure to also set $keyType
    protected $keyType="string";
}

Leave a Comment