2 Ways to Get User Agent Value from Request in Laravel

March 29, 2023
Laravel
2 Ways to Get User Agent Value from Request in Laravel

In this guide, we will share with you 2 ways to get the user agent from Request in laravel. Thanks to laravel which provides in-build Request class, which will allow us to get the user-agent.

By the end of the article, you will be able to get the user-agent and browser name of the user which is sending the request.

This tutorial is valid for all types of laravel versions including laravel 10, laravel 9, laravel 8, laravel 7 and laravel 6.

Lets get started!

Method 1: Get User Agent Using Request Server function

In this method, we are using Request in build class server function to get the user-agent.

Here is how you will write in the controller:

//your controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    //
    public function index(Request $request){

        $user_agent = $request->server('HTTP_USER_AGENT');
    }

In the above code, you can see we are using the Request $request in-built library and accessing it server function in which we are passing HTTP_USER_AGENT which will give us user-agent.

Method 2: Get User Agent Using Request Header function

In this method, we will use Request library with its Header function in order to get the user agent from the request. Here is how you do in the controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    //
    public function index(Request  $request){

        $user_agent = $request->header('User-Agent');
    }

In the above coder, we are using Request $request in-built library and accessing it header function. And in the header function we are are passing User-Agent to get the user-agent from the current request.

Output

Here is how the output of both above code will look like:

- Mozilla/5.0 (Windows NT 10.0; Win64; x64) 
- AppleWebKit/537.36 (KHTML, like Gecko) 
- Chrome/98.0.4758.102 Safari/537.36

Which gives the browser name, user-agent, browser and operating system.

Conclusion

In the above article, we have discussed 2 ways of getting the user-agent, and browser from the request using server and header from Request in-built library of laravel.

Let us know if you have any questions, see you in the next one.

Write a Reply or Comment

Your email address will not be published. Required fields are marked *


Icon