How to add headers in Guzzle http

How to add headers in Guzzle http

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Resolving Header Injection Errors in Laravel and Guzzle

When integrating a third-party API into a Laravel application, authentication is often handled via HTTP headers, specifically using an access_token. A common stumbling block for developers occurs when attempting to inject these headers dynamically within a controller method. If you encounter the error Undefined property: Symfony\Component\HttpFoundation\HeaderBag::$access_token, the issue likely stems from a fundamental misunderstanding of how Laravel's request object handles incoming data versus how it should be used to construct outgoing requests.

The specific code snippet in question attempts to retrieve an access token using $request->headers->access_token and pass it directly into Guzzle's get or post methods. This approach fails because the $request variable inside the controller method represents the incoming HTTP request from your own application's router, not the data intended for the external API. Unless the incoming request itself contains an access_token header sent by a client (like a browser or mobile app), accessing that property on the Laravel request object will result in a null value or, in some contexts, trigger the undefined property error if the code logic assumes its existence without checking.

In Guzzle, headers are passed as an associative array within the options argument. The syntax $this->client->get($url, ['headers' => ['access_token' => $value]]) is correct for the Guzzle client itself. However, the value being assigned to access_token in the problematic code ($request->headers->access_token) is incorrect because it pulls from the wrong source. You are trying to pass a header down from a controller method that likely does not receive that specific token in the incoming request context.

To fix this, you must determine where the access_token actually resides in your application's architecture. If the token is stored globally (e.g., in an environment variable, a dedicated configuration file, or a service class), you should retrieve it from that source rather than trying to parse it from the current request object. If the token needs to come from the incoming request—for example, if this endpoint acts as a proxy—the logic must first validate that the header exists before attempting to pass it along.

Here is a corrected approach assuming the token is available in your application's configuration or environment:

use Illuminate\Support\Facades\Http; // Or use your existing client instance
use GuzzleHttp\Exception\ClientException;

public function post(Request $request)
{
    try {
        // Retrieve the method and URL from the incoming request
        $method = $request->input('url_method');
        $url = $request->input('url');
        
        // Define headers based on available data
        // Option A: Token is in environment/config
        $headers = [
            'access_token' => config('services.api.token'), 
            'Content-Type' => 'application/json'
        ];

        // Option B: Token comes from the incoming request header (if applicable)
        // if ($token = $request->header('access_token')) {
        //     $headers['access_token'] = $token;
        // }

        $guzzleMethod = match($method) {
            'get' => 'get',
            'post' => 'post',
            default => throw new \Exception('Invalid Method')
        };

        // Execute the request using Guzzle
        $response = $this->client->$guzzleMethod($url, [
            'headers' => $headers,
            // Add body if method is POST and data exists
            'json' => $request->input('request_data') ?? [], 
        ]);

        // Decode the response body
        $decodedData = json_decode($response->getBody()->getContents(), true);

        return response()->json(['data' => $decodedData], $response->getStatusCode());

    } catch (ClientException $e) {
        // Handle specific HTTP errors from Guzzle
        return response()->json([
            'data' => 'Invalid Request: ' . $e->getMessage(),
            'status' => $e->getResponse()->getStatusCode()
        ], 400);
    } catch (\Exception $e) {
        return response()->json(['data' => 'Server Error'], 500);
    }
}

The key takeaway is that Guzzle expects the header array to be populated with valid values before the request is sent. Relying on $request->headers implies you are forwarding a header from an upstream client, but if your endpoint is accepting a method and URL string as input parameters, the authentication token must be injected into the outgoing request explicitly.

If you frequently need to handle complex API integrations with varying authentication schemes, consider abstracting the Guzzle client logic into a dedicated service class. This keeps your controllers clean and ensures that header management is centralized. For more advanced scenarios involving queue jobs or background tasks where headers are critical, ensure the token is passed securely via job payloads or environment variables rather than relying on request data that might not be available in those contexts.

Our network