Search code examples
laravellaravel-form

Call to a member function fails() on array error when using laravel Request classses


I'm using a custom request class for laravel form validations.

This is my request class

class ContactUsRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'lname' => 'required'
        ];
    }

   /**
   * Get the error messages for the defined validation rules.
   *
   * @return array
   */
    public function messages()
    {
        return [
            'lname.required' => 'please enter the last name'
        ];
    }

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }
}

And this is where I call it,

public function send(ContactUsRequest $request) {
        $validator = $request->validated();

        if ($validator->fails()) {
            return redirect('/contactus')
                            ->withErrors($validator)
                            ->withInput();
        } else {
            ContactUs::create($request->all());

            return redirect('/contactus');
        }
    }

But when I input correct values I get this,

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR) Call to a member function fails() on array


Solution

  • That's because request object automatically do that for you and you don't need to redirect back manually and $validator variable contains validated inputs so in your case you don't need to do anything and you can remove if and redirect safely

    public function send(ContactUsRequest $request) {
                ContactUs::create($request->validated());
    
                return redirect('/contactus');
            }
        }