Search code examples
phplaravellaravel-5

Laravel Validator (Get Attribute Names in Replacer)


The question I want to ask is about how to get the attributes name or display the attributes name with custom validator.

    $validator = Validator::make($request->all(), $model->get_update_rules());
    $validator->setAttributeNames(["attribute_name" => "Beauty Name"]);

The code above is the code I use to create the validator.
The code below is the code that I use to create Custom Validator.

Validator::extend ( 'custom_validator', function ($attribute, $value, $parameters, $validator) {
        return false;
    } );
    Validator::replacer('custom_validator', function($message, $attribute, $rule, $parameters) {
        return str_replace(":other", $parameters[1], $message);
    });

the $parameters[1] give me attribute_name instead of Beauty Name. How can i display the Beauty Name in my custom validator?


Solution

  • Finally i solve the problem by extending the Validator that provided by Laravel.

    use Illuminate\Validation\Validator;
    use Symfony\Component\Translation\TranslatorInterface;
    use DB;
    use Illuminate\Support\Facades\Input;
    class CustomValidator extends Validator{
        public function __construct(TranslatorInterface $translator, array $data, array $rules, array $messages = [], array $customAttributes = [])
        {
            parent::__construct($translator, $data, $rules, $messages, $customAttributes);
        }
    
        protected function validateCustomValidator($attribute, $value, $parameters){
            return false;
        }
    
        protected function replaceCustomValidator($message, $attribute, $rule, $parameters){
            return str_replace(':other', $this->getAttribute($parameters[1]), $message);
        }
    }
    

    The above code is use to create CustomValidator which extend the Validator that provided by Laravel. In your service providers, you have to add in the code as below to resolve your CustomValidator.

    use Illuminate\Support\ServiceProvider;
    use App\Validator\CustomValidator;
    use Validator;
    class ValidatorServiceProvider extends ServiceProvider
    {
        /**
         * Bootstrap the application services.
         *
         * @return void
         */
        public function boot()
        {
            Validator::resolver(function($translator, $data, $rules, $messages, $customAttributes)
            {
                return new CustomValidator($translator, $data, $rules, $messages, $customAttributes);
            });
        }
    
        /**
         * Register the application services.
         *
         * @return void
         */
        public function register()
        {
            //
        }
    }
    

    Remember to add this line inside you config/app.php

        App\Providers\ValidatorServiceProvider::class