YieldStudio / nova-phone-field

Nova Phone Number field with a dynamic mask based on the country code inserted by the user.
Other
6 stars 4 forks source link

Field ignores unique validation #6

Closed furyozo closed 1 year ago

furyozo commented 1 year ago

First off, thank you so much for implementing this package, it helped me and my team a lot. :)

Way to replicate the issue:

Display a nested resource inside Nova creation form using Laravel\Nova\Fields\HasOne relationship. In the nested resource fields() method define a PhoneNumber as follows:

use YieldStudio\NovaPhoneField\PhoneNumber;

...

PhoneNumber::make(static::transField('phone'), 'phone')
                ->onlyCountries(PhoneNumberValidity::PHONE_NUMBER_COUNTRIES)
                ->rules($phoneNumberValidity->phoneNumber()->nullable()->addRule((new Unique($usersTable, 'phone'))->ignoreModel($this->resource))->toArray()),

The unique constraint validation rule will not get applied when submitting the form.

After replacing the PhoneNumber field with a Laravel\Nova\Fields\Text field, the unique constraint validation gets applied succesfully.

For now I have circumvented this feature by using a custom rule as such:

PhoneNumber::make(static::transField('phone'), 'phone')
                ->onlyCountries(PhoneNumberValidity::PHONE_NUMBER_COUNTRIES)
                ->rules([
                    $phoneNumberValidity->phoneNumber()->nullable()->addRule((new Unique($usersTable, 'phone'))->ignoreModel($this->resource))->toArray(),
                    new UserPhoneUniqueRule(),
                ]),

But I would still love to be able to use the default rules() method in a way consistent with the Laravel\Nova\Fields\Field public function rules($rules) method.

furyozo commented 1 year ago

Ad.:

Moving the Illuminate\Validation\Rules\Unique into the array in place of the custom UserPhoneUniqueRule as such:

PhoneNumber::make(static::transField('phone'), 'phone')
                ->onlyCountries(PhoneNumberValidity::PHONE_NUMBER_COUNTRIES)
                ->rules([
                    $phoneNumberValidity->phoneNumber()->nullable()->toArray(),
                    (new Unique($usersTable, 'phone'))->ignoreModel($this->resource)
                ]),

also seems to work correctly.

furyozo commented 1 year ago

The issue was in the phone number formatting logic on our side