Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaration of formatErrors() should be compatible with FormRequest::formatErrors in laravel

Tags:

php

laravel

For using Form Request Validation in laravel, I created a StoreCourseRequest class like this :

namespace App\Http\Requests;

    use App\Http\Requests\Request;
    use Illuminate\Validation\Validator;

class StoreCourseRequest extends Request
    {
        public function authorize ()
        {
            return true;
        }

        public function rules ()
        {
            return [
                'title'       => 'required',
                'description' => 'required'
            ];
        }

        public function messages ()
        {
            return [
                'title.required'       => 'عنوان دوره را وارد کنید',
                'description.required' => 'توضیحات دوره را وارد کنید',
            ];
        }


        protected function formatErrors(Validator $validator)
        {

            $result = ['success' => false, 'msg' => $validator->errors()->first()];

return $result;
            }

        }

Because all request sends as Ajax, I want to customize format of error messages as you see in above code.

But after sending request , error below is occurred :

ErrorException in StoreCourseRequest.php line 9:
Declaration of App\Http\Requests\StoreCourseRequest::formatErrors() should be compatible with Illuminate\Foundation\Http\FormRequest::formatErrors(Illuminate\Contracts\Validation\Validator $validator)

I think that all things is right and follow docs instruction to create formrequest Class but i do not know what is that error and Why occurs?

like image 462
A.B.Developer Avatar asked Apr 17 '16 10:04

A.B.Developer


2 Answers

Change the beginning of your file to:

namespace App\Http\Requests;

    use App\Http\Requests\Request;
    use Illuminate\Contracts\Validation\Validator;

As you can see in the error message, FormRequest::formatErrors() method requires $validator param to be instance of Illuminate\Contracts\Validation\Validator, but you have imported use Illuminate\Validation\Validator;

like image 112
Oliver Maksimovic Avatar answered Sep 28 '22 15:09

Oliver Maksimovic


The error message states that your declaration of the method formatErrors is incompatible with that of the parent class you are trying to override.

You are aliasing Illuminate\Validation\Validator to Validator, but the method expects a validator of the type Illuminate\Contracts\Validation\Validator. Try changing the imported Validator class.

Thus, change line ~4 from:

use Illuminate\Validation\Validator;

to

use Illuminate\Contracts\Validation\Validator;

like image 30
Elias Avatar answered Sep 28 '22 16:09

Elias