'Laravel validation - how to return back with errors from Request on fail?

On validation fail, I have 2 situations

  • one when I display a new error page (this is how it was done before in the app)
  • I have a form and I redirect back with input (my problem)

The app is catching the ValidationException in the exceptions Handler - so there is no back with errors for me if a request fails. Now, I need to return back to the input with errors - from the request class, before it throws the standard ValidationException.

How do I do that from the request class pls?

The code is very basic

I have some rules...

I imagine I need a hook like - validationFailed().. in the request class?

Edit: - not API - regular monolithic PHP

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Auth;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $user = Auth::user();

        return [
            'new_location_code' => 'required|string|max:255|exists:xxx,code',
        ];
    }

    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'new_location_code.not_in' => 'xxx',
            'new_location_code.exists' => 'yyy',
        ];
    }

    //I need something like this
    public function validationFailed()
    {
        return redirect()->back()->withErrors($this->validator)->withInput();;
    }
}


Solution 1:[1]

Normally the FormRequest Class will redirect back to the Form Page with inputs and validation errors. That's the default functionality.

public function validationFailed() {
    return redirect()->back()->withErrors($this->validator)->withInput();;
}

You don't require the above code if you are passing the FormRequest class in the POST call of the Form like so

use App\Http\Requests\LocationCodeRequest;

public function store(LocationCodeRequest $request) { 
    // Code after validation
}

You can try by adding this in the LocationCodeRequest file.

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

protected function failedValidation(Validator $validator) {
        // Add redirection here. Errorbag and Inputs shud be available in session or can be passed here
        //throw new HttpResponseException(response()->json($validator->errors(), 422));
} 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1