Laravel form validation unique using 2 fields

前端 未结 5 1656
渐次进展
渐次进展 2020-12-15 08:09

How can I have a unique validation rule on 2 fields?

a. The application should not allow two people to have the same identical first name and last name.

It i

5条回答
  •  悲哀的现实
    2020-12-15 08:28

    This is an extensive answer to this question and how to create Laravel custom validator generally, you can simply copy and paste, and try to understand later: Step 1: Create a provider app/Providers/CustomValidatorProvider.php

    validators as $class) {
                $customValidator = new $class();
                ValidatorFacade::extend($customValidator->getName(), function() use ($customValidator) {
                    //set custom error messages on the validator
                    func_get_args()[3]->setCustomMessages($customValidator->getCustomErrorMessages());
                    return call_user_func_array([$customValidator, "validate"], func_get_args());
                });
                ValidatorFacade::replacer($customValidator->getName(), function() use ($customValidator) {
                    return call_user_func_array([$customValidator, "replacer"], func_get_args());
                });
            }
        }
    
        /**
         * Register the application services.
         *
         * @return void
         */
        public function register() {
            //
        }
    
    }
    

    Step 2: Update your app.php in your config folder config/app.php to include your created provider in the provider array

    App\Providers\CustomValidatorProvider::class,
    

    Step 3: Create your custom validator, in my case, I am creating multiple unique fields validator app/Validators/MultipleUniqueValidator.php

    name;
        }
    
        /**
         *
         * @param string $message
         * @param string $attribute
         * @param string $rule
         * @param array $parameters
         * @return string
         */
        public function replacer(string $message, string $attribute, string $rule, array $parameters): string {
            unset($parameters[0]);
            $replacement = implode(", ", $parameters);
            $replacement = str_replace("_", " ", $replacement);
            $replacement = Str::replaceLast(", ", " & ", $replacement);
            $replacement = Str::title($replacement);
            return str_replace(":fields", "$replacement", $message);
        }
    
        /**
         * 
         * @param string $attribute
         * @param mixed $value
         * @param array $parameters
         * @param Validator $validator
         * @return bool
         * @throws \Exception
         */
        public function validate(string $attribute, $value, array $parameters, Validator $validator): bool {
            $model = new $parameters[0];
            if (!$model instanceof Model) {
                throw new \Exception($parameters[0] . " is not an Eloquent model");
            }
            unset($parameters[0]);
            $this->fields = $parameters;
    
            $query = $model->query();
            $request = app("request");
            foreach($parameters as $parameter){
                $query->where($parameter, $request->get($parameter));
            }
    
            return $query->count() == 0;
        }
    
        /**
         * Custom error messages
         * 
         * @return array
         */
        public function getCustomErrorMessages(): array {
            return [
                $this->getName() => ":fields fields should be unique"
            ];
        }
    
    }
    

    Now you can do this in your request

    'ANY_FIELD_CAN_CARRY_IT' => 'required|numeric|multiple_unique:'.YOUR_MODEL_HERE::class.',FIELD_1,FIELD_2,FIELD_3...',
    

提交回复
热议问题