wim91's avatar

How can I check the uniqueness of multiple fields in one record?

Hello everyone. Here's the task. Four images are added through a form. Each image has a name that is saved in the database. When updating files, I need to delete the previously saved image, upload a new one, and overwrite its name. It's possible that the new file name will match the names of three other files. My question is, how can I check the name of the uploaded file against the names of the other files, each of which is stored in the database? I found an example that only checks one field, and I have four.

$myId = 1;
$validated = $request->validate([
    'mydata' => 'unique:table,mydata,' . $myId,
]);

PS: The task requires that file names be changed, which could easily have been solved by assigning a unique name to each newly uploaded file, but alas...

0 likes
5 replies
Glukinho's avatar

Add multiple unique rules each with it's own table/column?

wim91's avatar

Do you mean it like this?

$myId = 1;
$validated = $request->validate([
    'mydata' => 'unique:table,mydata,' . $myId. '|unique:table,mydata_2,' . $myId,
]);

It doesn't work that way for me...

Glukinho's avatar

It's because you're misusing unique rule: https://laravel.com/docs/12.x/validation#rule-unique

'mydata' => 'unique:table,mydata,' . $myId - this doesn't check uniqueness of $myId. This rule is intended to check if request mydata field is unique in mydata column of table table. You shouldn't pass real values into this rule, the rule takes checked value from a request.

Can you show your real request with real fields and real table rows and what exactly should be unique?

wim91's avatar

Thanks for the answers. I solved the problem by creating my own rule and passing the ID of the desired record to it.

Please or to participate in this conversation.