Md. Obydullah Howdy, I am Md. Obydullah from Bangladesh. I love to write the article which will help others. It's my passion.

Laravel Detect Device is Mobile or Desktop

Published on April 13, 2019 1 min read

Hi, we can easily detect any device in Laravel by using a package. Just follow these simple steps:

Table of Contents

  1. Install Package
  2. Config app.php
  3. Create Routes
  4. Use in Blade File

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 Howdy, I am Md. Obydullah from Bangladesh. I love to write the article which will help others. It's my passion.

Leave a Reply

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