Reputation: 2000
I have a table called contacts
that has contact_id
and user_id
.
I want to make the combination of these 2 fields unique and validate them. So what I have done in my migration is this:
$table->integer('user_id');
$table->integer('contact_id');
$table->timestamps();
$table->unique(['user_id', 'contact_id']);
This makes the combination unique, and when I try to insert a duplicate with this code:
Contact::create([
'contact_id' => $request->input('contact_id'),
'user_id' => $request->input('user_id'),
]);
return redirect(route('person-search'));
I get this error:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1-2' for key 'contacts.contacts_user_id_contact_id_unique' (SQL: insert into `contacts` (`contact_id`, `user_id`, `updated_at`, `created_at`) values (2, 1, 2020-12-05 09:26:09, 2020-12-05 09:26:09))
Instead of this error, I want to make a validation for these 2 columns and show a custom error to my user. How can I write a validation for that?
Upvotes: 1
Views: 161
Reputation: 42721
As explained in the documentation, you can write custom validation rules easily. The callback function receives the field's name and value, as well as a callback you can use to emit an error message.
So, just write something that does a database query for the two values. As a quick and dirty example I would never put into production:
$validator = Validator::make($request->all(), [
'contact_id' => [
function($k, $v, $f) {
$result = DB::table('contacts')
->select('*')
->where('contact_id', $v)
->where('user_id', request()->user_id)
->first();
if ($result) {
$f("Duplicate value");
}
}
],
...
]);
Another option would be wrap the creation in try/catch and throw a ValidationException
if the creation fails due to that error.
Upvotes: 1