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

Mobiledetectlib Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

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

Implementation Patterns

1. Constructor-Based Injection with Config

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
]);

2. Middleware for Device-Based Routing or Optimization

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);
    }
}

3. PSR-16 Cache Integration

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).

4. Cloudflare / Proxy Compatibility

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());

5. Unit Testing with Mocked Detection

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());
}

Gotchas and Tips

  • 🚨 v4.8+ requires explicit setUserAgent() or autoInitOfHttpHeaders: true
    If you see "User-Agent is empty" exceptions, check that either:

    • You’re calling setUserAgent() or setHttpHeaders() before detection, or
    • Your config includes 'autoInitOfHttpHeaders' => true (default).
  • 🧠 Tablets are mobileisMobile() 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).

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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport