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?
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;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With