Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Devicedetector Laravel Package

dungeonworx/laravel-devicedetector

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dungeonworx/laravel-devicedetector
    

    Publish the config (optional):

    php artisan vendor:publish --provider="Dungeonworx\DeviceDetector\DeviceDetectorServiceProvider" --tag="config"
    
  2. First Use Case: Detect device type in a controller or middleware:

    use Dungeonworx\DeviceDetector\Facades\DeviceDetector;
    
    $device = DeviceDetector::detect($request->userAgent());
    $isMobile = $device->isMobile();
    $isTablet = $device->isTablet();
    $browser = $device->getBrowserName();
    
  3. Middleware Integration: Add the middleware to your HTTP kernel (app/Http/Kernel.php):

    protected $middleware = [
        \Dungeonworx\DeviceDetector\Middleware\DeviceDetectorMiddleware::class,
    ];
    

    Now, $request->device will be populated with the detected device info.


Implementation Patterns

Common Workflows

1. Request-Based Detection

Use the middleware to automatically attach device data to the request:

// In a controller
$device = $request->device;
if ($device->isBot()) {
    return redirect()->route('bot-page');
}

2. Facade Usage

Access device data anywhere in your app via the facade:

$device = DeviceDetector::detect($userAgent);
$os = $device->getOperatingSystem();
$deviceType = $device->getDeviceType();

3. Conditional Logic

Use device detection for feature flags or UI adjustments:

if (DeviceDetector::detect($request->userAgent())->isMobile()) {
    return view('mobile.home');
}
return view('desktop.home');

4. Caching Detected Devices

Cache results for performance (e.g., in middleware):

$cacheKey = 'device_' . md5($request->userAgent());
$device = cache()->remember($cacheKey, now()->addHours(1), function () use ($request) {
    return DeviceDetector::detect($request->userAgent());
});

5. Custom Device Rules

Extend detection logic by subclassing the detector:

use Dungeonworx\DeviceDetector\DeviceDetector as BaseDetector;

class CustomDetector extends BaseDetector {
    public function isCustomDevice() {
        return $this->getDeviceType() === 'custom';
    }
}

Integration Tips

  • User-Agent Parsing: Always pass the raw User-Agent string from $request->userAgent() for accurate detection.

  • Middleware Order: Place DeviceDetectorMiddleware before other middleware that relies on $request->device.

  • Testing: Mock the detector in tests:

    $this->app->instance('deviceDetector', Mockery::mock('Dungeonworx\DeviceDetector\DeviceDetector'));
    
  • Performance: Avoid redundant detection calls. Cache results or reuse the middleware-populated $request->device.


Gotchas and Tips

Pitfalls

  1. Outdated Dependencies: The package relies on piwik/device-detector (last updated in 2018). User-Agent strings may not be fully supported for modern devices. Consider supplementing with custom logic for newer devices.

  2. Middleware Overhead: The middleware runs on every request, which may impact performance if not cached. Use caching (e.g., cache()->remember) to mitigate this.

  3. Config Overrides: The published config (config/devicedetector.php) may not be loaded by default. Ensure it’s published and merged if customizing behavior.

  4. Facade vs. Middleware: The facade (DeviceDetector) and middleware ($request->device) may return slightly different instances if not synchronized. Prefer one approach per project.

  5. Bot Detection: Bot detection (e.g., $device->isBot()) may yield false positives. Test thoroughly with known bots (e.g., Googlebot, Slackbot).


Debugging Tips

  1. Inspect Raw Data: Dump the full device object to debug:

    dd(DeviceDetector::detect($request->userAgent())->getData());
    
  2. User-Agent Testing: Use tools like User-Agent String to test detection accuracy.

  3. Middleware Debugging: Add a temporary dump in the middleware to verify $request->device is populated:

    \Dungeonworx\DeviceDetector\Middleware\DeviceDetectorMiddleware::class => function ($request, $next) {
        \Log::debug('Device detected:', $request->device);
        return $next($request);
    },
    
  4. Custom Rules: If extending detection, log intermediate values to debug:

    \Log::debug('Device type:', $this->getDeviceType());
    \Log::debug('Client:', $this->getClient());
    

Extension Points

  1. Custom Device Types: Extend the DeviceDetector class to add custom device types or override detection logic:

    class ExtendedDetector extends \Dungeonworx\DeviceDetector\DeviceDetector {
        public function isWearable() {
            return in_array($this->getDeviceType(), ['smartwatch', 'smartglass']);
        }
    }
    

    Bind the extended class in AppServiceProvider:

    $this->app->bind('deviceDetector', function () {
        return new ExtendedDetector();
    });
    
  2. Event Listeners: Trigger events when specific devices are detected (e.g., for analytics):

    // In EventServiceProvider
    protected $listen = [
        'device.detected' => [
           \App\Listeners\LogDeviceDetection::class,
       ],
    ];
    
  3. Service Provider Overrides: Override the default service provider to customize initialization:

    // config/app.php
    'providers' => [
        // ...
        App\Providers\CustomDeviceDetectorServiceProvider::class,
    ],
    
  4. View Composers: Use device detection in view composers to conditionally load assets:

    View::composer('*', function ($view) {
        $device = app('deviceDetector')->detect(request()->userAgent());
        $view->with('isMobile', $device->isMobile());
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope