Tiến Marion
Tiến Marion

Reputation: 109

Laravel: Add custom validation class make fail attributes() method in Request class

I have code in Request class:

public function rules()
{
    return [
        'id' => 'required|check_xxx',
    ];
}

public function attributes()
{
    return [
        'id' => 'AAA',
    ];
}

As you can see. I have cusom validation method name check_xxx. This method in inside class CustomValidator.

So, I have code:

class ValidationServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->app->validator->resolver(function ($translator, $data, $rules, $messages) {
            return new CustomValidator($translator, $data, $rules, $messages);
        });
    }
}

And error message for required is: Please input :attribute

But I got the message: Please input id, (TRUE is: Please input AAA)

I discovered that $this->app->validator->resolver make attributes() method in Request is useless.

How can I fix that? Thank you.

Upvotes: 1

Views: 107

Answers (1)

Muhammad Adnan
Muhammad Adnan

Reputation: 165

I had this issue in Laravel 5.2 but found a QUICK solution as following. In example following you will add rule directly inside the APP Provider.

File to add rule: app/Providers/AppServiceProvider.php

public function boot()
    {
        // ....

        #/
        #/ Adding rule "even_number" to check even numbers.
        #/ 
        \Validator::extend('even_number', function($attribute, $value, $parameters, $validator) {
              $value = intval($value);
              return ($value % 2) == 0);

        // ...

    }

Upvotes: 1

Related Questions