Laravel Detect Mobile or Desktop Using jenssegers/agent Example

Laravel 6 , Laravel , Laravel 7

Nicesnippets

16657

03-06-2020


In this artical, i will let you know how to detect mobile or desktop browser in laravel application. we will use jenssegers/agent package for detect device. we can easily detect device mobile or tablet or desktop.

jessenger ajent plugin provide method to get all user agent values with their pre define function by package. they provide function like isMobile(), isTablet(), isDesktop() and device().

Install jessenger/ajent Package


We need to install jessenger/ajent package by composer. Go to Laravel project folder and run this command:

composer require jenssegers/agent

After that you need to set providers and alias.

config/app.php

.....

'providers' => [

....

Jenssegers\Agent\AgentServiceProvider::class,

]

'aliases' => [

....

'Agent' => Jenssegers\Agent\Facades\Agent::class,

]

.....

Create Routes

Let’s create routes to detect devices.

routes/web.php

Detect Mobile:

Route::get('detect', function () {

$agent = new \Jenssegers\Agent\Agent;

$result = $agent->isMobile();

if ($result)

return "Yes, This is Mobile.";

else

return "No, This is not Mobile.";

});

Detect Desktop:

Route::get('detect', function () {

$agent = new \Jenssegers\Agent\Agent;

$result = $agent->isDesktop();

if ($result)

return "Yes, This is Desktop.";

else

return "No, This is not Desktop.";

});

Detect Tablet:

Route::get('detect', function () {

$agent = new \Jenssegers\Agent\Agent;

$result = $agent->isTablet();

if ($result)

return "Yes, This is Tablet.";

else

return "No, This is not Tablet.";

});

Use in Blade File

@if((new \Jenssegers\Agent\Agent())->isDesktop())

{{-- your code --}}

@endif

@if((new \Jenssegers\Agent\Agent())->isMobile())

{{-- your code --}}

@endif

It will help you.....


Recommended Posts