user3652775
user3652775

Reputation: 221

Laravel add error message to validator in custom form request

I have a custom form request where I do some extra validation logic and I want to add an error if my logic fails but I get this error:

Call to a member function errors() on null

Here is my custom Request:

if (!empty($this->get('new_password')) && !empty($this->get('current_password'))) {
    if (
        !Auth::attempt([
            'email' => $this->get('email'),
            'password' => $this->get('current_password'),
            'status' => 'pending'
        ])
    ) {
        $this->validator->errors()->add('current_password', 'Something is wrong with this field!');
    }
}

return [                    
    'first_name' => 'required|min:1|max:190',        
];

EDIT complete class

class ProfileRequest extends FormRequest
{
    public function authorize()
    {
        return Auth::check();
    }

    public function rules()
    {
        if (!empty($this->get('new_password')) && !empty($this->get('current_password'))) {
            if (
                !Auth::attempt([
                'email' => $this->get('email'),
                'password' => $this->get('current_password'),
                'status' => 'pending'
                ])
            ) {
                $this->validator->getMessageBag()->add('current_password', 'Something is wrong with this field!');
            }
        }

        return [
            'first_name'       => 'required|min:1|max:190',
        ];
    }
}

Upvotes: 0

Views: 2130

Answers (1)

Amit Senjaliya
Amit Senjaliya

Reputation: 2945

I think you need to add the hook withValidator as laravel doc suggested.

public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($this->somethingElseIsInvalid()) {
            $validator->errors()->add('field', 'Something is wrong with this field!');
        }
    });
}

Upvotes: 6

Related Questions