0

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',
        ];
    }
}
4
  • Call to a member function errors() on null means $this->validator is null. Please check where you have initialised $this->validator Commented Feb 18, 2020 at 9:44
  • @Sehdev it comes from the FormRequest that extens my custom form request laravel.com/docs/5.8/validation#creating-form-requests Commented Feb 18, 2020 at 9:45
  • can you pots the whole class code? Commented Feb 18, 2020 at 9:50
  • @V-K see edit for full code Commented Feb 18, 2020 at 9:56

1 Answer 1

6

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!');
        }
    });
}
Sign up to request clarification or add additional context in comments.

6 Comments

where do I call this withValidator() function then?
@user3652775 In the form request file.
it doesnt make sense to me I am sorry
@user3652775 Please read this doc for more understand: laravel.com/docs/5.8/validation#form-request-validation
I don't see or read where I need to call this function: withValidator($validator) It just says I can make it. Okay I put it in my ProfileRequest but it's never called?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.