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.
Connect with KoderSolution 🚀
Master modern software engineering, scalable architectures, and advanced backend systems.
Read more architectural deep-dives, systems tutorials, and engineering guides on kodersolution.com.
Subscribe to @kodersolution for concise, animated system design breakdowns and technical shorts.
Follow our official page for daily development tips, architecture discussions, and community updates.
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.