Home > database >  Adding failedValidation() function to Request gives error with Illuminate\Contracts\Validation\Va
Adding failedValidation() function to Request gives error with Illuminate\Contracts\Validation\Va

Time:09-26

I'm trying to add a failedValidation() function to a custom Request. I've googled some examples in what I assume are much older Laravel versions (I'm using 9.15), but when I try to add it it gives the error:

Declaration of App\Http\Requests\BasketRequest::failedValidation() must be compatible with Illuminate\Foundation\Http\FormRequest::failedValidation(Illuminate\Contracts\Validation\Validator $validator)

The weird thing is that I can add passedValidation() just fine. So what's the problem? Or rather, how do I fix it, because the framework's code for the validation goes a bit over my head.

Also how can I add additional variables to the return back() that the validation executes out of sight somewhere?

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    protected function passedValidation()
    {
        dd('passedValidation');
    }

    protected function failedValidation()
    {
        dd('failedValidation');
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [];
    }
}

CodePudding user response:

As the error you're getting says, the failedValidation method within a FormRequest object expects a single parameter which is an instance of the Validator class.

So to resolve this error, you need to update the failedValidation signature in your BasketRequest:

// Don't forget to include this use statement at the top
use Illuminate\Contracts\Validation\Validator;

protected function failedValidation(Validator $validator)
{
    // ...
}

The weird thing is that I can add passedValidation() just fine

Not weird at all considering the passedValidation function doesn't have any arguments.

Also how can I add additional variables to the return back() that the validation executes out of sight somewhere?

Not sure what you mean by this, however, you could either use a hook, or customise the response in your failedValidation function.

protected function failedValidation(Validator $validator)
{
    $response = redirect()
        ->route('route.name.here')
        ->with('Avast', 'Yarr, Walk the plank!')
        ->withErrors($validator);

    throw (new ValidationException($validator, $response))
        ->errorBag($this->errorBag)
        ->redirectTo($this->getRedirectUrl());
}
  • Related