How to get User-Agent header in Laravel

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

Introduction

When building web applications, understanding the client’s environment can be pivotal for delivering the right content and enhancing user experiences. The User-Agent HTTP header contains a characteristic string that lets servers and network peers identify the application, operating system, vendor, or version of the requesting user agent. Laravel, being a modern PHP framework, makes accessing the User-Agent straightforward.

Accessing the User-Agent Header in Laravel

The most basic way to access the User-Agent in Laravel is by using the Request facade. Here is a simple example:

<?php

use Illuminate\Http\Request;

Route::get('/user-agent', function (Request $request) {
    return $request->header('User-Agent');
});

If you navigate to the /user-agent route of your Laravel application, this will output the User-Agent string.

Handling User-Agent in Controllers

Instead of fetching User-Agent directly in the route, the more common approach is to do so within a controller method. Here’s how you might implement this:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function userAgent(Request $request)
    {
        $userAgent = $request->header('User-Agent');
        // ... Perform operation with $userAgent
        return view('user-agent', compact('userAgent'));
    }
}

In the example above, the $userAgent variable is being passed to a view, allowing you to utilize it within your HTML templates.

Middleware for User-Agent Handling

For applications needing to handle User-Agent in a more global scope, creating a middleware might be the right choice. This way, you can manage or modify requests based on User-Agent before they reach your application logic.

<?php

namespace App\Http\Middleware;

use Closure;

class CheckUserAgent
{
    public function handle($request, Closure $next)
    {
        $userAgent = $request->header('User-Agent');
        
        // Check or modify the $userAgent or request if necessary
        
        return $next($request);
    }
}

After creating your middleware, don’t forget to register it in your app/Http/Kernel.php file to assign it to a route group or as global middleware.

Advanced User-Agent Parsing

While retrieving the User-Agent string is useful, parsing it to extract detailed information is often more so. Laravel doesn’t have built-in capabilities to parse User-Agent strings, but you can easily integrate a package like whichbrowser/parser for robust parsing. Here’s a start:

composer require whichbrowser/parser

Then in your controller or middleware:

<?php

use WhichBrowser\Parser;

$userAgentString = $request->header('User-Agent');
$parsedUserAgent = new Parser($userAgentString);

// Now you can access properties like
$parsedBrowser = $parsedUserAgent->browser->name;
$parsedOS = $parsedUserAgent->os->name;

With this, you’re now obtaining granular details about the browser and operating system of the user’s device, which could be quite insightful for analytics or conditional content rendering.

Testing the User-Agent Logic

In Laravel, testing is a critical part of the development workflow. Here’s how you can write a test to ensure your User-Agent logic works well:

<?php

namespace Tests\Feature;

use Tests\TestCase;

class UserAgentTest extends TestCase
{
    public function testUserAgentEndpoint()
    {
        $response = $this->withHeaders([
            'User-Agent' => 'TestAgent'
        ])->get('/user-agent');

        $response->assertSee('TestAgent');
    }
}

In this test, we’re setting a custom User-Agent header and asserting that our application correctly reveals it.

Conclusion

Understanding how to access and parse User-Agent strings can enhance the sophistication of your Laravel application. Whether it’s tailoring responses to different browsers, conducting analytics, or enhancing security, the User-Agent holds key information about the client that Laravel developers can exploit efficiently. With the use of Laravel’s Request class, middleware, or third-party packages, the process is both straightforward and versatile.