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 User-Agent and HTTP headers. Provides simple checks like isMobile() and isTablet(), regularly updated with device rules, and easy to install via Composer for any PHP app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require mobiledetect/mobiledetectlib
    

    Use version ^4.11 for Laravel (PHP 8.2+).

  2. Basic Usage:

    use Detection\MobileDetect;
    
    $detect = new MobileDetect();
    if ($detect->isMobile()) {
        // Mobile-specific logic
    }
    
  3. First Use Case: Redirect mobile users to a mobile-optimized URL in Laravel middleware:

    use Detection\MobileDetect;
    
    public function handle($request, Closure $next)
    {
        $detect = new MobileDetect();
        if ($detect->isMobile() && !$request->is('mobile/*')) {
            return redirect()->route('mobile.home');
        }
        return $next($request);
    }
    

Key Entry Points

  • isMobile(): Detects phones/tablets (returns bool).
  • isTablet(): Explicit tablet detection.
  • getUserAgent(): Access raw User-Agent string.
  • setHttpHeaders(): Manually set headers (useful for testing).

Implementation Patterns

Core Workflows

  1. Middleware Integration:

    // app/Http/Middleware/MobileDetectMiddleware.php
    public function handle($request, Closure $next)
    {
        $detect = new MobileDetect();
        $request->merge(['is_mobile' => $detect->isMobile()]);
        return $next($request);
    }
    

    Access via $request->is_mobile in controllers/views.

  2. Dynamic View Logic:

    @if($request->is_mobile)
        @include('mobile.partial')
    @else
        @include('desktop.partial')
    @endif
    
  3. API Feature Gating:

    if ($detect->isMobile() && $detect->isTablet()) {
        return response()->json(['features' => ['touch-optimized']]);
    }
    

Advanced Patterns

  • Caching User-Agent Parsing (for long-running processes):

    $detect = new MobileDetect([
        'cache' => new \Detection\Cache\Cache(
            new \Psr\SimpleCache\CachePool([
                'psr16' => new \Symfony\Component\Cache\Adapter\FilesystemAdapter()
            ])
        )
    ]);
    
  • Custom Device Detection: Extend the library by overriding regex patterns:

    $detect->setUserAgent('Custom-UA');
    if ($detect->match('CustomDeviceRegex')) {
        // Handle custom device
    }
    
  • CloudFront/Proxy Headers:

    $detect->setHttpHeaders([
        'HTTP_CF_CONNECTING_IP' => $request->ip(),
        'HTTP_USER_AGENT' => $request->userAgent()
    ]);
    

Laravel-Specific Tips

  1. Service Provider Binding:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(MobileDetect::class, function () {
            return new MobileDetect(['autoInitOfHttpHeaders' => true]);
        });
    }
    
  2. Request Macro:

    // app/Providers/AppServiceProvider.php
    public function boot()
    {
        Request::macro('isMobile', function () {
            return app(MobileDetect::class)->isMobile();
        });
    }
    

    Usage: $request->isMobile().

  3. Testing:

    $detect = new MobileDetect();
    $detect->setUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X)');
    $this->assertTrue($detect->isMobile());
    

Gotchas and Tips

Common Pitfalls

  1. Missing User-Agent:

    • Error: No user-agent has been set (since v4.8.01).
    • Fix: Ensure autoInitOfHttpHeaders is true (default) or manually set:
      $detect->setHttpHeaders($_SERVER);
      
  2. Cache Bloat:

    • Issue: Unbounded memory growth in long-running processes (e.g., Laravel Octane).
    • Fix: Configure cache size:
      $cache = new \Detection\Cache\Cache(new \Psr\SimpleCache\CachePool(), 1000); // Max 1000 entries
      $detect = new MobileDetect(['cache' => $cache]);
      
  3. Regex Overrides:

    • Gotcha: Custom regex arrays must be strings or string arrays (not mixed types).
    • Fix: Use:
      $detect->setRegex('CustomDevice', ['iPhone', 'iPad']);
      
  4. PHP 8.4 Implicit Nulls:

    • Issue: Deprecated in PHP 8.4 (affects v4.8.01+).
    • Fix: Update to ^4.9.0 for compatibility.

Debugging Tips

  1. Inspect Raw Data:

    $detect->setUserAgent($request->userAgent());
    dd($detect->getUserAgent(), $detect->getHttpHeaders());
    
  2. Test User-Agents: Use the demo site to validate detection logic.

  3. Cache Debugging:

    $detect->getCache()->evictExpired(); // Manually clean expired entries
    

Extension Points

  1. Custom Cache Backends: Implement Psr\SimpleCache\CacheInterface and inject:

    $detect = new MobileDetect([
        'cache' => new \Detection\Cache\Cache(new \RedisCache())
    ]);
    
  2. Override Detection Logic: Extend the class and override methods like isMobile():

    class CustomMobileDetect extends MobileDetect {
        public function isMobile() {
            return parent::isMobile() && $this->isTouchScreen();
        }
    }
    
  3. HTTP Headers: Use Sec-CH-UA-Mobile (Chrome 114+) for modern detection:

    $detect->setHttpHeaders([
        'HTTP_SEC_CH_UA_MOBILE' => '?0'
    ]);
    

Configuration Quirks

  • maximumUserAgentLength: Default 500 (truncates longer strings).

  • cacheKeyFn: Customize key generation (e.g., for multi-tenant apps):

    $detect = new MobileDetect([
        'cacheKeyFn' => fn($key) => "tenant_{$tenantId}_{$key}"
    ]);
    
  • autoInitOfHttpHeaders: Set to false if using custom headers (e.g., in tests).

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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle