2 Methods to Get Request Header in Laravel 9

2 Methods to Get Request Header in Laravel 9

During client and server communication, additional information to request or response can be added by using HTTP headers. This tutorial provides 2 methods how to get request header in Laravel 9 application.

Method 1 - 'header' method of 'Request' object

Illuminate\Http\Request object has a method named header which allows retrieving a header by its name. A header name is case-insensitive, so we can use User-Agent, user-agent, USER-AGENT etc.

app/Http/Controllers/TestController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

class TestController extends Controller
{
    public function index(Request $request): Response
    {
        $header = $request->header('User-Agent');

        return new Response($header);
    }
}

Method 2 - 'header' method of 'Request' facade

Laravel provides the Illuminate\Support\Facades\Request facade which allows getting a header by its name using header method.

app/Http/Controllers/TestController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;
use Illuminate\Support\Facades\Request;

class TestController extends Controller
{
    public function index(): Response
    {
        $header = Request::header('User-Agent');

        return new Response($header);
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.