In this tutorial, we will learn how to detect devices is mobile or desktop in Laravel.
Detect mobile or desktop in Laravel
In Laravel, you can use the agent
method provided by the Jenssegers\Agent
package to detect whether the user's device is a mobile or desktop.
Follow the below steps to detect devices
Step 1: Install the package
First, you need to install the Jenssegers/Agent
package using Composer. Enter the following command into your terminal and run.
composer require jenssegers/agent
Step 2: Set up middleware (Optional)
You can create a middleware to detect the device in every request. Create a new middleware using the following command.
php artisan make:middleware DetectDevice
Open the generated DetectDevice.php
file in the app/Http/Middleware
directory and modify the handle
method.
<?php
namespace App\Http\Middleware;
use Closure;
use Jenssegers\Agent\Agent;
class DetectDevice
{
public function handle($request, Closure $next)
{
$agent = new Agent();
if ($agent->isMobile()) {
// Set a flag or perform actions for mobile devices
// For example, you can use $request->attributes->add(['is_mobile' => true]);
} else {
// Set a flag or perform actions for desktop devices
// For example, you can use $request->attributes->add(['is_mobile' => false]);
}
return $next($request);
}
}
Step 3: Register the middleware
Add the newly created middleware to the $routeMiddleware
array in the app/Http/Kernel.php
file.
protected $routeMiddleware = [
// ...
'detectDevice' => \App\Http\Middleware\DetectDevice::class,
];
Step 4: Apply the middleware
You can apply the middleware globally, to a group of routes, or to specific routes. For example, to apply it globally, add the following line to the $middleware
array in the app/Http/Kernel.php
file.
protected $middleware = [
// ...
\App\Http\Middleware\DetectDevice::class,
];
Now, the isMobile
method from the Jenssegers\Agent
package can be used throughout your application to detect the user's device type. Adjust your application logic based on the detected device type as needed.