Reputation: 221
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',
];
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
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