Laravel get request headers

Learn laravel get request headers with practical examples, diagrams, and best practices. Covers php, laravel, oauth-2.0 development techniques with visual explanations.

Accessing Request Headers in Laravel

Hero image for Laravel get request headers

Learn how to retrieve and utilize various HTTP request headers within your Laravel applications, crucial for authentication, API interactions, and debugging.

HTTP request headers carry vital metadata about a client's request, such as authentication tokens, content types, user agents, and more. In Laravel, accessing these headers is straightforward, allowing you to build robust and secure applications. This article will guide you through the different methods to retrieve request headers, focusing on common use cases like OAuth 2.0 token validation.

Retrieving All Request Headers

Laravel's Request object provides a convenient way to access all incoming HTTP headers. You can inject the Illuminate\Http\Request instance into your controller methods or resolve it from the service container. The headers property of the request object returns a Symfony\Component\HttpFoundation\HeaderBag instance, which allows you to interact with the headers.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HeaderController extends Controller
{
    public function showHeaders(Request $request)
    {
        // Get all headers as an array
        $allHeaders = $request->headers->all();

        // You can also use the header() helper function
        // $allHeaders = header(); // This is for response headers, not request headers

        // To get all request headers using the Request object:
        $allRequestHeaders = $request->header(); // Returns all headers as an associative array

        return response()->json($allRequestHeaders);
    }
}

Example of retrieving all request headers in a Laravel controller.

Accessing Specific Headers

Often, you'll only need to retrieve a specific header, such as Authorization, Accept, or User-Agent. The Request object offers several methods for this purpose, providing flexibility and convenience. These methods are case-insensitive, making it easier to work with varying header casing.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SpecificHeaderController extends Controller
{
    public function getSpecificHeader(Request $request)
    {
        // Get a single header value
        $userAgent = $request->header('User-Agent');

        // Get a header with a default value if it doesn't exist
        $contentType = $request->header('Content-Type', 'application/json');

        // Get the Authorization header, common for OAuth 2.0 tokens
        $authorizationHeader = $request->header('Authorization');

        return response()->json([
            'User-Agent' => $userAgent,
            'Content-Type' => $contentType,
            'Authorization' => $authorizationHeader
        ]);
    }
}

Retrieving specific request headers using the header() method.

Working with OAuth 2.0 Authorization Headers

For APIs secured with OAuth 2.0, the Authorization header is paramount. It typically contains a bearer token. Laravel's Request object simplifies extracting this token, which can then be used to authenticate the user or validate their permissions. This is a common pattern in API development.

sequenceDiagram
    participant Client
    participant LaravelApp
    participant AuthServer

    Client->>LaravelApp: API Request (Authorization: Bearer <token>)
    LaravelApp->>LaravelApp: Get 'Authorization' header
    LaravelApp->>LaravelApp: Extract Bearer token
    LaravelApp->>AuthServer: Validate token (optional, if not stateless)
    AuthServer-->>LaravelApp: Token valid / invalid
    LaravelApp-->>Client: API Response (200 OK / 401 Unauthorized)

Sequence diagram for handling OAuth 2.0 Authorization headers in a Laravel application.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class OAuthController extends Controller
{
    public function protectedRoute(Request $request)
    {
        $authorizationHeader = $request->header('Authorization');

        if (!$authorizationHeader || !str_starts_with($authorizationHeader, 'Bearer '))
        {
            return response()->json(['message' => 'Unauthorized: Bearer token missing or invalid'], 401);
        }

        $token = substr($authorizationHeader, 7); // Extract token after 'Bearer '

        // In a real application, you would now validate this token
        // e.g., against a database, an OAuth server, or using a JWT library.
        // For demonstration, we'll just return the token.

        return response()->json([
            'message' => 'Access granted!',
            'token' => $token
        ]);
    }
}

Extracting and basic validation of an OAuth 2.0 Bearer token.