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

Avatar
C

Callum Davies

Senior Backend Engineer••
8046Views
5mRead
0Reactions

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.

 

Connect with KoderSolution 🚀

Master modern software engineering, scalable architectures, and advanced backend systems.

What's your setup?How does your production stack handle background jobs? Are you using Redis with Horizon, or cloud queues like AWS SQS?
Callum Davies
C
Written by•Senior Backend Engineer

Callum Davies

PHP & Laravel practitioner since v5.4. Big believer in thin controllers, explicit return types, and boring modular architecture that doesn't page you on weekends.

React to this article

Recommended Articles

View all articles