diego182/mobile-detect
Symfony bundle wrapper for Mobile Detect. Provides auto-configuration and autowiring so you can inject a MobileDetect service into your app to detect mobile/tablet devices from the user agent with minimal setup.
Installation
composer require diego182/mobile-detect
Register the service provider in config/app.php:
'providers' => [
// ...
Diego182\MobileDetectBundle\MobileDetectServiceProvider::class,
],
Basic Usage
Inject the MobileDetect service into a controller or service:
use Diego182\MobileDetectBundle\MobileDetect;
public function __construct(private MobileDetect $detect) {}
public function checkDevice(Request $request) {
if ($this->detect->isMobile()) {
return response()->json(['device' => 'mobile']);
}
return response()->json(['device' => 'desktop']);
}
First Use Case Redirect mobile users to a mobile-optimized URL:
if ($this->detect->isMobile()) {
return redirect()->to('/mobile');
}
Device-Specific Logic
Use isMobile(), isTablet(), or isBot() to conditionally render views or APIs:
if ($this->detect->isTablet()) {
return view('tablet.view');
}
User-Agent Parsing Extract device details (e.g., OS, browser) for analytics:
$os = $this->detect->getOsName();
$browser = $this->detect->getBrowserName();
Middleware Integration Create middleware to enforce device restrictions:
namespace App\Http\Middleware;
use Closure;
use Diego182\MobileDetectBundle\MobileDetect;
class MobileOnly
{
public function __construct(private MobileDetect $detect) {}
public function handle($request, Closure $next) {
if (!$this->detect->isMobile()) {
abort(403, 'Mobile devices only.');
}
return $next($request);
}
}
API Versioning Route mobile traffic to a lightweight API endpoint:
Route::middleware(['mobile.detect'])->group(function () {
Route::get('/api/v1/mobile', 'MobileController@index');
});
Caching Headers User-agent strings can change frequently. Avoid caching responses based solely on device detection unless explicitly needed.
False Positives Some bots/tablets may misclassify. Test edge cases:
if ($this->detect->isMobile() && !$this->detect->isTablet()) {
// Only mobile phones
}
Performance Overhead
Parsing user-agent strings adds minimal overhead, but avoid calling MobileDetect in critical loops.
\Log::debug('User-Agent:', [$request->userAgent()]);
mobile-detect). Monitor for updates to the base package.Custom Device Rules
Extend the detector by subclassing MobileDetect:
class CustomMobileDetect extends \Mobile_Detect {
public function isCustomDevice() {
return $this->is('CustomDeviceName');
}
}
Register the custom class in the service provider.
Integration with Laravel Scout Use device detection for search personalization:
if ($this->detect->isMobile()) {
$results = Product::search($query)->mobileResults()->get();
}
Configuration
Override default settings via config/mobile-detect.php:
'tablet_user_agents' => [
'iPad', // Add custom tablet agents
],
How can I help you explore Laravel packages today?