Laravel exists validation: Should not pass when user and product are already stored

Viewed 30

I have a product_votes table which stores for each user and product a value. The value can either be 1 or -1 which is equal to an upvote or downvote. A user can only either up- or downvote a product and that only one time as user_id, product_id and value are unique.

But a user can change his vote. He can upvote a product and then downvote it afterwards, or the other way around.

Now I am trying to write a validation rule which checks whether the user has already upvoted a product or not. So, basically if there already exists a record with the value 1 for the specific user with the id e.g., 13 and the specific product with the id e.g., 5.

For some reason, my validation does not work. The user always has the possibility to upvote a product multiple times. But I want the validation to fail and return a response with 'You have already upvoted this product.'

This is my validation in the FormRequest for a downvote (value -1) request:

public function rules(): array
{
    return [
        'value' => [
            'required',
            'regex:/^[1]$/',
            Rule::unique('product_votes', 'value')
                ->where('user_id', Auth::user()->id)
                ->where('product_id', $this->route('product')->id)
                ->where('value', -1)
        ],
    ];
}

The value 1 being sent via the transfer has NOTHING to do with the value being stored for the user and product in the votes table. This value is only needed to be able to execute a custom validation.

Do you guys know where my mistake is and what I did wrong?

Kind regards

0 Answers
Related