Reputation: 41
I have a table where there is a composite uniqe key.
I want to validate it before creating the record, so the HTTP request won't return with some SQL error(Integrity constraint violation: 1062 Duplicate entry).
I'm using Laravel 9.
The composite unique key is: user_id, work_id, date (basically u can't work on the same stuff multiple times on the same day) Only the work_id and the date comes from the $request, the user_id comes from auth()->user()->id;
My current code is:
$fields = $request->validate([
'work_id' => 'required|integer',
'date' => 'required|date',
]);
But somehow I have to add the validation rule, I explained above, but I have no idea how.
I tried:
Googling it but I haven't found anything useful to me. I've seen a libary which is supposed to solve this, but it was for Laravel 4.
Upvotes: 3
Views: 589
Reputation: 18926
You can use the built in rule unique
, to also have a where clause including your user_id
column.
'work_id' => [
'required',
'integer',
Rule::exists('your_table', 'work_id')->where('user_id', $request->user()->id),
];
It did not seem like you specified the table naming, replace your_table
.
Upvotes: 1