dungeonworx/laravel-devicedetector
Installation:
composer require dungeonworx/laravel-devicedetector
Publish the config (optional):
php artisan vendor:publish --provider="Dungeonworx\DeviceDetector\DeviceDetectorServiceProvider" --tag="config"
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();
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.
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');
}
Access device data anywhere in your app via the facade:
$device = DeviceDetector::detect($userAgent);
$os = $device->getOperatingSystem();
$deviceType = $device->getDeviceType();
Use device detection for feature flags or UI adjustments:
if (DeviceDetector::detect($request->userAgent())->isMobile()) {
return view('mobile.home');
}
return view('desktop.home');
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());
});
Extend detection logic by subclassing the detector:
use Dungeonworx\DeviceDetector\DeviceDetector as BaseDetector;
class CustomDetector extends BaseDetector {
public function isCustomDevice() {
return $this->getDeviceType() === 'custom';
}
}
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.
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.
Middleware Overhead:
The middleware runs on every request, which may impact performance if not cached. Use caching (e.g., cache()->remember) to mitigate this.
Config Overrides:
The published config (config/devicedetector.php) may not be loaded by default. Ensure it’s published and merged if customizing behavior.
Facade vs. Middleware:
The facade (DeviceDetector) and middleware ($request->device) may return slightly different instances if not synchronized. Prefer one approach per project.
Bot Detection:
Bot detection (e.g., $device->isBot()) may yield false positives. Test thoroughly with known bots (e.g., Googlebot, Slackbot).
Inspect Raw Data: Dump the full device object to debug:
dd(DeviceDetector::detect($request->userAgent())->getData());
User-Agent Testing: Use tools like User-Agent String to test detection accuracy.
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);
},
Custom Rules: If extending detection, log intermediate values to debug:
\Log::debug('Device type:', $this->getDeviceType());
\Log::debug('Client:', $this->getClient());
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();
});
Event Listeners: Trigger events when specific devices are detected (e.g., for analytics):
// In EventServiceProvider
protected $listen = [
'device.detected' => [
\App\Listeners\LogDeviceDetection::class,
],
];
Service Provider Overrides: Override the default service provider to customize initialization:
// config/app.php
'providers' => [
// ...
App\Providers\CustomDeviceDetectorServiceProvider::class,
],
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());
});
How can I help you explore Laravel packages today?