Laravel Detect Device is Mobile or Desktop
Hi, we can easily detect any device in Laravel by using a package. Just follow these simple steps:
Table of Contents
Step 1 : Install Package
We need to install jessenger/ajent package by composer. Go to Laravel project folder and run this command:
composer require jenssegers/agent
Step 2 : Config app.php
Now we need to set provider and alias. Navigate to config/app.php and add Jenssegers classes to providers and aliases like this:
app.php
'providers' => [
....
Jenssegers\Agent\AgentServiceProvider::class,
]
'aliases' => [
....
'Agent' => Jenssegers\Agent\Facades\Agent::class,
]
Step 3 : Create Routes
Let’s create routes to detect devices. Open routes/web.php and create routes like these:
Detect Mobile:
web.php
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 Phone:
Route::get('detect', function () {
$agent = new \Jenssegers\Agent\Agent;
$result = $agent->isPhone();
if ($result)
return "Yes, This is Phone.";
else
return "No, This is not Phone.";
});
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.";
});
Detect Robot:
Route::get('detect', function () {
$agent = new \Jenssegers\Agent\Agent;
$result = $agent->isRobot();
if ($result)
return "Yes, This is Robot.";
else
return "No, This is not Robot.";
});
Step 4 : Use in Blade File
@if((new \Jenssegers\Agent\Agent())->isDesktop())
{{-- your code --}}
@endif
@if((new \Jenssegers\Agent\Agent())->isMobile())
{{-- your code --}}
@endif
Thank you.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.