Reputation: 303
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
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
Reputation: 1559
Can't guess why you change primary key like that but you can:
Upvotes: 2