mobiledetect/mobiledetectlib
Lightweight PHP library to detect mobile devices and tablets using the User-Agent and HTTP headers. Simple API to check for phones, tablets, OS and browsers. Actively maintained (4.8.x) with older LTS/deprecated branches available.
Install the package via Composer:
composer require mobiledetect/mobiledetectlib
In Laravel, bind MobileDetect as a singleton in AppServiceProvider::register() to inject it wherever needed:
use Detection\MobileDetect;
use Illuminate\Support\Facades\Request;
$this->app->singleton(MobileDetect::class, function () {
$detect = new MobileDetect();
// v4.8+ requires explicit user agent — this works automatically with default config
$detect->setUserAgent(Request::userAgent());
return $detect;
});
✅ First use case — conditionally render views based on device type in Blade:
@inject('detect', 'Detection\MobileDetect')
@if($detect->isMobile() && !$detect->isTablet())
<link rel="stylesheet" href="/css/mobile.css">
@elseif($detect->isTablet())
<link rel="stylesheet" href="/css/tablet.css">
@else
<link rel="stylesheet" href="/css/desktop.css">
@endif
Use config-driven instantiation for flexibility (especially in tests or jobs):
$detect = new MobileDetect([
'autoInitOfHttpHeaders' => true, // default, safe for CLI/web
'maximumUserAgentLength' => 256, // truncate long UAs
]);
class DeviceAwareMiddleware
{
public function handle($request, Closure $next)
{
$detect = new MobileDetect();
$detect->setUserAgent($request->userAgent());
// Skip heavy JS/CSS for mobile, or enforce AMP
view()->share('isMobile', $detect->isMobile());
view()->share('isTablet', $detect->isTablet());
return $next($request);
}
}
Cache detection results to avoid repeated UA parsing (critical in high-traffic apps):
$detect = new MobileDetect([
'cache' => app(\Psr\SimpleCache\CacheInterface::class),
]);
if ($detect->isMobile()) {
// Reuse cached result elsewhere
}
⚠️ In v4.8.09+, cache keys use
sha1()by default to avoid Laravel storage errors (see issue #974).
When behind reverse proxies, headers like X-Forwarded-Proto may be present but HTTP_USER_AGENT may be missing. Use setHttpHeaders():
$detect = new MobileDetect();
$detect->setHttpHeaders($request->headers->all());
Enable modern Client Hints (v4.8.07+):
// Auto-uses `Sec-CH-UA-Mobile` if available (e.g., Chrome 93+)
$detect->setUserAgent($request->userAgent());
Create reusable test helpers:
public function it_detects_iphone_14()
{
$detect = new MobileDetect();
$detect->setUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 16_5 like Mac OS X) AppleWebKit/605.1.15');
$this->assertTrue($detect->isMobile());
$this->assertFalse($detect->isTablet());
$this->assertEquals('iPhone', $detect->getDevice());
}
🚨 v4.8+ requires explicit setUserAgent() or autoInitOfHttpHeaders: true
If you see "User-Agent is empty" exceptions, check that either:
setUserAgent() or setHttpHeaders() before detection, or'autoInitOfHttpHeaders' => true (default).🧠 Tablets are mobile — isMobile() returns true for both phones and tablets by design.
Correct order:
if ($detect->isTablet()) { /* ... */ }
elseif ($detect->isMobile()) { /* ... */ }
else { /* desktop */ }
🧊 Cache hygiene in long-running processes
In queues/workers, expired entries accumulate. Call periodically:
$detect->getCache()->evictExpired();
🔑 Avoid cache key collisions
Since sha1 is default (v4.8.09+), no action needed — but if you customize cacheKeyFn, ensure keys are deterministic and short.
⏱ Don’t call detection in tight loops
Even though v4 is optimized, do one detection per request and store results in a DTO or shared variable — especially for analytics or bulk operations.
🌐 UA parsing is fallible — Mobile Detect is best for broad device categorization (mobile/tablet/desktop), not fine-grained model detection. For device-specific layout tweaks, combine with feature detection (e.g., JS navigator.userAgentData).
How can I help you explore Laravel packages today?