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

aronduby's avatar

JSON response with custom header

Can someone please explain to me why this works:

return response()
    ->json(compact('token'))
    ->header('Authorization', 'Bearer '.$token);

but this results in a Method header not found exception from Support\Traits\Macroable:

return response()
    ->header('Authorization', 'Bearer '.$token)
    ->json(compact('token'));
0 likes
4 replies
bobbybouwmann's avatar

You can pass in headers as the third result

return response()->json(compact('token'), 200, $headers);

The code from the framework:

/**
 * Return a new JSON response from the application.
 *
 * @param  string|array  $data
 * @param  int  $status
 * @param  array  $headers
 * @param  int  $options
 * @return \Illuminate\Http\JsonResponse
 */
public function json($data = [], $status = 200, array $headers = [], $options = 0);
3 likes
rodrigo.pedra's avatar
Level 56

The response() helper function, with no arguments, returns a ResponseFactory instance. This object has a ->json(...) method, but does not have a ->header(...) method.

On the other hand, the ->json(...) method from ResponseFactory returns a JsonResponse instance, which uses a ResponseTrait trait adding the ->header(...) to it.

So it will work in this order: response() => ResponseFactory => json() => JsonResponse => header(),

But not in this: response() => ResponseFactory => header() (method not found)

You can check the source code:

response() helper: [https://github.com/laravel/framework/blob/5.1/src/Illuminate/Foundation/helpers.php#L444-L463]

ResponseFactory: [ https://github.com/laravel/framework/blob/5.1/src/Illuminate/Routing/ResponseFactory.php#L74-L90 ]

JsonResponse: [ https://github.com/laravel/framework/blob/5.1/src/Illuminate/Http/JsonResponse.php#L8-L10 ]

ResponseTrait: [ https://github.com/laravel/framework/blob/5.1/src/Illuminate/Http/ResponseTrait.php#L27-L40 ]

5 likes
s24WebDev's avatar

This question is answered correctly but i wonder how to get the header in this response? Can you give me an advice please?

Please or to participate in this conversation.