3

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.

Gábor Stefler
  • 41
  • 1
  • 1
  • 7
  • Check this https://laravel.com/docs/9.x/validation#available-validation-rules – S N Sharma Mar 24 '22 at 07:19
  • @gábor-stefler you can write custom validation logic... Here is an documentation link https://laravel.com/docs/9.x/validation#custom-validation-rules – Vishal Mar 24 '22 at 07:27

1 Answers1

1

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.

mrhn
  • 17,961
  • 4
  • 27
  • 46