While App\Exceptions\Handler is gone in Laravel 11, there's a new way to achieve custom JSON responses for validation errors. Here's how you can do it using the withExceptions method in bootstrap/app.php:
PHP
use Illuminate\Validation\ValidationException;
$app->singleton(JsonExceptionHandler::class, function ($app) {
return new class extends JsonExceptionHandler {
public function renderForRequest(Request $request, Exception $e)
{
if ($e instanceof ValidationException) {
return response()->json([
'message' => $e->getMessage(),
'error' => SystemErrorCode::FormValidateFailed->value,
'data' => $exception->errors()
], 422); // Set your preferred status code here (e.g., 422 for Unprocessable Entity)
}
return parent::renderForRequest($request, $e);
}
};
});
This code defines a custom JsonExceptionHandler class that overrides the default renderForRequest method. Inside the method, you can check if the exception is a ValidationException and then return your desired JSON response with the error message, code, and data (similar to your previous approach).
Key points:
We use a singleton to register our custom exception handler.
The status code in the response can be adjusted based on your needs (e.g., 422 for validation errors).