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 to retrieve a header by it's 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 Illuminate\Support\Facades\Request facade which allows to get a header by it's 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.