Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

randm's avatar
Level 6

How to check if validation fail with form-request?

I am trying to write a CRUD for an API. However, when the validation fail, instead of redirecting the user to the home page, I want to return json based response with the errors.

I am able to do that using the following code

    public function store(Request $request)
    {
        try {
            $validator = $this->getValidator($request);

            if ($validator->fails()) {
                return $this->errorResponse($validator->errors()->all());
            }
            
            $asset = Asset::create($request->all());

            return $this->successResponse(
                'Asset was successfully added!',
                $this->transform($asset)
            );
        } catch (Exception $exception) {
            return $this->errorResponse('Unexpected error occurred while trying to process your request!');
        }
    }

    /**
     * Gets a new validator instance with the defined rules.
     *
     * @param Illuminate\Http\Request $request
     *
     * @return Illuminate\Support\Facades\Validator
     */
    protected function getValidator(Request $request)
    {
        $rules = [
            'name' => 'required|string|min:1|max:255',
            'category_id' => 'required',
            'cost' => 'required|numeric|min:-9999999.999|max:9999999.999',
            'purchased_at' => 'nullable|string|min:0|max:255',
            'notes' => 'nullable|string|min:0|max:1000',
            'picture' => 'nullable|string|min:0|max:255',
        ];

        return Validator::make($request->all(), $rules);
    }

Now, I like to extract some of my code into a form-request to clean up my controller little more. I like to change my code to something like the code below.

    public function store(AssetsFormRequest $request)
    {
        try {
            if ($request->fails()) {
                return $this->errorResponse($request->errors()->all());
            }            
            $asset = Asset::create($request->all());

            return $this->successResponse(
                'Asset was successfully added!',
                $this->transform($asset)
            );
        } catch (Exception $exception) {
            return $this->errorResponse('Unexpected error occurred while trying to process your request!');
        }
    }

As you can probably tell that $request->fails() and $request->errors()->all() is not going to work. How can I check if the request failed and then how can I get the errors out of the form-request?

For your reference, here is how my AssetsFormRequest class look like

    <?php
    
    namespace App\Http\Requests;
    
    use Illuminate\Foundation\Http\FormRequest;
    
    class AssetsFormRequest 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()
        {
            return [
                'name' => 'required|string|min:1|max:255',
                'category_id' => 'required',
                'cost' => 'required|numeric|min:-9999999.999|max:9999999.999',
                'purchased_at' => 'nullable|string|min:0|max:255',
                'notes' => 'nullable|string|min:0|max:1000',
            ];
        }
    }
0 likes
7 replies
SyedAbuthahir's avatar

You have more then one option.

Method 1 (FormRequest Class)

If you move to FormRequest class then you have a special protected method calld failedValidation.

add the following code snippet into your FormRequest Class

Example

protected void failedValidation(Validator $validator) {
    // Perform your response 
    // by default it will throw ValidationException.
}

Method 2 (ExceptionHandler Class)

You can globally in laravel application via handler class app/Exceptions/Handler.php Please change the method like below to perform global error handling.

public function render($request, Exception $exception)
{
    if( $exception instanceOf ValidationException)
    {
        // perofrm your response
    }
        return parent::render($request, $exception);
}
randm's avatar
Level 6

When I add the following method to my formRequest, I get an error

    /**
     * Handle a failed validation attempt.
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function failedValidation(Validator $validator)
    {
           dd('test');
    }

Here is the error

ReflectionException in RouteSignatureParameters.php line 25: 
Class App\Http\Requests\AssetsFormRequest does not exist

But when I don't add it, I get redirected to the main page when the validation fails

And yes, the AssetsFormRequest class exists.

I tried to do composer dump-autoload

Any idea why this isn't working?

2 likes
Snapey's avatar

@ssonia please check the date of the question before answering something from 5 years ago

shez1983's avatar

then u need to show the whole file.. for me to let u know why it isnt working.. i cant see a

class Name extends Request { ... your code makes me believe its just a function

Please or to participate in this conversation.