How to Detect Devices is Mobile or Desktop in Laravel 11 | websolutioncode.com
How to Detect Devices is Mobile or Desktop in Laravel 11 | websolutioncode.com

How to Detect if a Device is Mobile or Desktop in Laravel 11

Detecting whether a device is mobile or desktop can be useful in many scenarios, such as tailoring the user experience, displaying different content, or optimizing performance. Laravel, a popular PHP framework, makes it easy to detect device types using various methods and libraries. In this article, we will walk through how to detect device types in Laravel 11 with easy-to-follow steps and example code.

Prerequisites

  • Laravel 11 installed
  • Basic understanding of Laravel routes, controllers, and middleware

Step 1: Install the Mobile Detect Package

First, we need to install the “Mobile Detect” package, which helps in detecting mobile devices. This can be done using Composer:

composer require mobiledetect/mobiledetectlib

Step 2: Create a Middleware for Device Detection

Middleware is a convenient way to filter HTTP requests entering your application. We will create a middleware that uses the Mobile Detect package to determine the device type.

Run the following Artisan command to create middleware:

php artisan make:middleware DetectDevice

This command will create a new file named DetectDevice.php in the app/Http/Middleware directory.

Step 3: Implement Device Detection Logic

Open the DetectDevice.php file and implement the device detection logic. Here is how you can do it:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Mobile_Detect;

class DetectDevice
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $detect = new Mobile_Detect;

        if ($detect->isMobile()) {
            $device = 'mobile';
        } elseif ($detect->isTablet()) {
            $device = 'tablet';
        } else {
            $device = 'desktop';
        }

        // You can share this information with your views or controllers
        $request->merge(['device' => $device]);

        return $next($request);
    }
}

Step 4: Register Middleware

Next, we need to register our middleware in the app/Http/Kernel.php file. Add the following line to the $routeMiddleware array:

protected $routeMiddleware = [
    // Other middleware
    'detect.device' => \App\Http\Middleware\DetectDevice::class,
];

Step 5: Apply Middleware to Routes

Now, we can apply the middleware to our routes. Open the routes/web.php file and apply the middleware to the routes you want to protect:

use Illuminate\Support\Facades\Route;

Route::middleware(['detect.device'])->group(function () {
    Route::get('/', function (Request $request) {
        $device = $request->device;
        return view('welcome', compact('device'));
    });

    Route::get('/about', function (Request $request) {
        $device = $request->device;
        return view('about', compact('device'));
    });
});

Step 6: Display Device Type in Views

Finally, we can display the detected device type in our views. Open the resources/views/welcome.blade.php file and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Welcome</title>
</head>
<body>
    <h1>Welcome to our website!</h1>
    <p>You are using a {{ $device }} device.</p>
</body>
</html>

You can repeat this step for other views like about.blade.php.

Testing

To test if the device detection is working correctly, you can use different devices or browser developer tools to simulate various devices and view the output.

Conclusion

In this article, we have learned how to detect if a device is mobile or desktop in Laravel 11 using the Mobile Detect package. By following these simple steps, you can easily tailor the user experience based on the device type. This approach helps in optimizing the performance and usability of your web application.