How to extract request headers in Laravel

Updated: January 15, 2024 By: Guest Contributor Post a comment

Introduction

Laravel, being one of the most widely used PHP frameworks, simplifies many of the common tasks in web development, such as routing, authentication, sessions, and caching. A crucial part of handling HTTP requests in web applications is dealing with request headers. Headers can provide crucial context that influences how the request should be processed.

In this tutorial, we will explore different techniques to extract request headers in Laravel, covering basic to advanced examples along with output. We aim to provide you with a comprehensive guide that can serve both as a learning tool for new Laravel developers and as a reference for the more experienced ones.

Basic Extraction of Headers

The request object in Laravel provides an intuitive way to access headers. Let’s start with the basics:


// Using the Request Facade
to the operation
use Illuminate\Support\Facades\Request;

// Inside your controller method

$headerValue = Request::header('Header-Name');

This will retrieve the value of ‘Header-Name’ from the request headers. Remember to replace ‘Header-Name’ with the actual name of the header you are interested in.

Request Instance Method

In addition to the Request Facade, you can also extract headers directly from the request instance:


// Injecting the Request instance via method injection
public function handleRequest(Illuminate\Http\Request $request)
{
    $headerValue = $request->header('Header-Name');
    // Use $headerValue as needed
}

This instance method is generally preferable because of its explicitness and the ease of testing it allows.

Default Values

When you are not sure if a header will always be set, you can specify a default value:


$headerValue = Request::header('Header-Name', 'DefaultValue');

If ‘Header-Name’ is not found among the request headers, ‘DefaultValue’ will be returned instead.

Retrieving All Headers

Sometimes, you need to access all headers sent with the request. Here’s how you can do it :


$headers = Request::header();

// $headers will be an associative array where keys are the header names and the values are the corresponding header values

Note that header names are normalized to a lowercase representation in the resulting array.

Retrieving Multiple Values of a Single Header

Some HTTP headers, like ‘Accept’ or ‘Cookie’, can contain multiple values. Here’s how you can retrieve them:


$headerValues = Request::header('Header-With-Multiple-Values', []);

// $headerValues will be an array of string values

In the case of headers with multiple values, your specified default should be an empty array.

Headers In Middleware

Laravel’s middleware is a convenient place to handle headers. Here’s an example of how to work with headers in a middleware setting:


// Middleware handle method
public function handle($request, Closure $next)
{
    $headerValue = $request->header('Header-Name');

    // You might perform some logic based on header value.

    return $next($request);
}

In middleware, you have the full Request instance at your disposal, allowing you to work with headers as needed before the request reaches your controllers.

Advanced Usage

In more complex applications, you might need to perform conditional checks or manipulate headers in a more granular way. You can use collection methods on the headers, as they are returned as a collection:


$headers = collect(Request::header());

// Check if a particular header exists
if ($headers->has('Header-Name')) {
    // Do something
}

Using collections gives you access to a rich API for filtering, mapping, and reducing data.

Testing Header Access

When writing tests, you can simulate incoming headers using Laravel’s testing methods:


$response = $this->withHeaders([
    'Header-Name' => 'Header-Value',
])->json('POST', '/endpoint', ['data' => 'payload']);

This will create a POST request to ‘/endpoint’ with the specified headers and payload.

Response Headers

Extracting headers is usually done on the request, but sometimes you might want to inspect response headers:


$response = $response->withHeaders([
    'Header-Name' => 'Header-Value',
]);

$headerValue = $response->headers->get('Header-Name');

In this code, we are attaching headers to a response and then retrieving one of them.

Conclusion

Extracting headers in Laravel is straightforward yet flexible. The framework provides various mechanisms tailored to different scenarios, promoting clean and testable code. Whether through facades, instances, or middleware, you have the tools necessary to handle request headers effectively.