Mutevu
Mutevu

Reputation: 303

How can I restrict duplicate primary key in laravel model?

I am working on a laravel project in which I have set a custom primary key. However, the project allows two different entries to have the same value in the field set as primary key. How do I restrict this?

I have set the public $incrementing property on my model to false and also set the protected $keyType property to string.

class Students extends Model
{
    protected $primaryKey = 'reg_no';
    public $incrementing = false;
    protected $keyType = 'string';
}

I expected that the code will raise an error if I enter two records will the same value in the 'reg_no' field, which is defined as primary, but the record is being saved without an error.

Upvotes: 0

Views: 1025

Answers (2)

Aditya Thakur
Aditya Thakur

Reputation: 2610

You can set it to unique in your migration

Schema::table('students', function($table)
{
    $table->string('reg_no')->unique(); 
});

For more information: https://laravel.com/docs/5.8/migrations#creating-indexes

Upvotes: 1

MohamedSabil83
MohamedSabil83

Reputation: 1559

Can't guess why you change primary key like that but you can:

  • Set the column as unique in migration.
  • use a unique validation rule to prevent duplicate entry.

Upvotes: 2

Related Questions