Use a String as a Custom Primary Key for Eloquent Table In Laravel
Laravel

Use a String as a Custom Primary Key for Eloquent Table In Laravel

In this article, I will share with you, how to set a custom primary key in the laravel model, so that, you can use any custom column name as you want.

Sometimes we do not need timestamps in our table, we can also disable timestamps in the model.

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.

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 $timestamps = false;
    public $incrementing = false;

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

I hope, it will solve your problem to set a string as a primary key.

 

Get The latest Coding solutions.

Subscribe to the Email Newsletter