Laravel Rules Unique if

Viewed 35

I have some hard times with Laravel Rules (importing csv file). I'm trying to use the Rule::unique function but when another field is not empty, for example:

public function rules(): array
    {
        return [
            'code' => ['required', 'string', Rule::unique('product_gift_cards', 'code')],
            'pin' => ['nullable'],
            'sequence_number' => ['nullable']
        ];
    }

So this code, should be unique only when sequence_number is not filled. When sequence_number is filled with something, the code should not be unique. I have deleted the unique index in the database, so it will work if I write is as needed, any suggestions?

1 Answers

These are the validation rules in Laravel: https://laravel.com/docs/9.x/validation#available-validation-rules

Sadly there's no unique_if rule here.

One possible solution here is you have to validate it manually. You check if the input has file uploaded using $this->hasFile('sequence_number').

$code_rules = ['required', 'string'];

// Check if sequence_number is NOT uploaded
if (! $this->hasFile('sequence_number')) {
    $code_rules[] = Rule::unique('product_gift_cards', 'code');
}

return [
    'code' => $code_rules,
    'pin' => ['nullable'],
    'sequence_number' => ['nullable']
];
Related