Skip to content

Conversation

chuoke
Copy link
Contributor

@chuoke chuoke commented Oct 10, 2025

This PR changes Handler::prepareJsonResponse() to use response()->json() instead of new JsonResponse() directly, ensuring consistency when developers customize the ResponseFactory.

Problem

When developers extend ResponseFactory to customize JSON response behavior (e.g., adding custom headers, wrapping response data, or using a custom JsonResponse subclass), the customization applies everywhere EXCEPT in exception responses, because Handler::prepareJsonResponse() directly instantiates JsonResponse.

Solution

We have 3 ways to maintain consistency.

  • Customize the exception handler response
  • Enable prepareJsonResponse support callback like the shouldReturnJson method
  • Make exception handler use response factory (this PR)

Use the response()->json() helper, which respects custom ResponseFactory implementations.

For example, we customized the JSON response like this:

$this->app->singleton(ResponseFactoryContract::class, function ($app) {
            return new class($app['view'], $app['redirect']) extends ResponseFactory
            {
                public function json($data = [], $status = 200, array $headers = [], $options = 0)
                {
                    $msg = $data['message'] ?? $data['msg'] ?? null;
                    if ($msg) {
                        unset($data['message']);
                        $wrapData = [
                            'msg' => $msg,
                            'success' => $status >= 200 && $status < 300,
                        ] + $data;
                    } else {
                        $wrapData = [
                            'msg' => 'success',
                            'success' => true,
                            'data' => $data,
                        ];
                    }

                    return new JsonResponse($wrapData, 200, $headers, $options);
                }
            };
        });

Before PR, the exception response:

{
    "message": "Server Error"
}

We can see that did not use our customized JSON format.

After PR:

{
    "msg": "Server Error",
    "success": false
}

@taylorotwell taylorotwell merged commit e359739 into laravel:12.x Oct 10, 2025
46 of 68 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants