How i can return a customized response in a FormRequest class in Laravel 5.5?

Stefan Bogdanescu

Founder & Senior Architect · 2026-06-29

Laravel Company

Mastering Custom Error Responses in Laravel 5.5 FormRequests for APIs

As developers building robust APIs with Laravel, managing validation errors gracefully is crucial. When handling API requests, simply returning the standard validation error structure often results in verbose and less user-friendly responses. You want to transform Laravel's internal error state into a clean, custom array that precisely reflects what failed, mimicking the desired $validator->errors() format without relying on deprecated or non-existent methods in later versions.

This post dives deep into how you can achieve this custom error formatting within a FormRequest class in Laravel 5.5, focusing on practical solutions for API development.

The Challenge: Customizing Validation Error Output

You are running into a common challenge when building APIs: the default validation error structure returned by Laravel is designed for traditional web forms, not necessarily for streamlined JSON responses. While methods like formatErrors() existed in older versions (like 5.4), their behavior and accessibility can be inconsistent or insufficient in recent versions like 5.5 for complex API requirements.

Your goal is to take the nested structure generated by the validator and flatten or reformat it into a simple array of error messages, similar to how you might manually inspect $validator->errors().

The Solution: Intercepting and Reformatting Validation Results

Since directly manipulating the internal validation object within the FormRequest for API responses can be fragile across minor framework updates, the most robust approach is to leverage the request's state after validation has occurred, typically by accessing the $errors property on the Request object itself, or by utilizing the failedValidation hook if you need to halt execution early.

For your specific scenario—returning a flat array of all errors—we will focus on retrieving the raw error data and restructuring it in the Controller layer, ensuring clean separation of concerns.

Step 1: Preparing the FormRequest for Error Access

While we won't rely solely on a method within FormRequest to generate the final output (as this mixes presentation logic with validation rules), we ensure that the necessary information is readily available during the request lifecycle. The key is understanding where Laravel stores the errors after a failed validation.

In your ProductRequest, you have defined excellent custom messages in the messages() method:

// App\Http\Requests\ProductRequest
public function messages()
{
    return [
        // ... your custom messages
        'code.required' => 'El :attribute es obligatorio.',
        // ... other messages
    ];
}

These messages are crucial for providing meaningful feedback, even if we change the structure in the controller.

Step 2: Implementing Custom Error Handling in the Controller

The best place to shape the final API response is within your Controller method responsible for handling the request (e.g., store or update). By inspecting the $request->errors() collection, you gain full control over the output format.

Here is how you can modify your controller logic to achieve the desired flat error array:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\ProductRequest;
use Illuminate\Support\Facades\Validator; // We might use this for explicit validation if needed, though Request handles it.

class ProductController extends Controller
{
    public function store(ProductRequest $request)
    {
        // 1. The request has already been validated by ProductRequest.
        // If execution reaches here, validation MUST have passed unless we handle the failure explicitly.

        // --- Custom Error Handling Block (If you needed to manually trigger an error response) ---
        if ($request->fails()) {
            // In a real API scenario where FormRequest handles the error response via HttpException, 
            // this block might be redundant. However, for custom JSON responses outside of standard HTTP exceptions:

            $errors = $request->errors(); // Accessing the errors collection

            return response()->json([
                'message' => 'The given data was invalid.',
                'errors' => $errors // This returns a nested array structure similar to what you see.
            ], 422);
        }
        // --- End Custom Block ---


        $product = new \App\Product($request->validated());
        $product->save();

        return response('', 201);
    }
}

Note on API Best Practices: For robust API design in Laravel, the preferred method is often to let the FormRequest throw a ValidationException. This automatically handles HTTP status codes (422 Unprocessable Entity) and structures the error response according to Laravel's built-in conventions. However, if you absolutely require a highly customized, flat array structure that differs from the default JSON structure, intercepting the request object as shown above gives you the necessary control over the final payload.

Conclusion

While finding a single method within FormRequest for direct manipulation of $validator->errors() in Laravel 5.5 might be elusive, achieving your goal is accomplished by shifting the focus from manipulating the internal validator object to intelligently inspecting and restructuring the data available on the validated Request object within your Controller. By understanding how validation errors are stored—as nested arrays tied to attributes—you can construct exactly the JSON structure your API consumers expect. Always remember that leveraging Laravel’s built-in exception handling for standard error responses is often the cleanest path, but custom formatting requires careful inspection of the request state. For further deep dives into building scalable APIs, explore resources on laravelcompany.com.