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 class to detect mobile phones and tablets using User-Agent plus HTTP headers. Identify device type and specific platforms/brands for responsive content, analytics, or redirects. Widely used and actively maintained via tagged major branches.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require mobiledetect/mobiledetectlib
    

    Use version ^4.10 for Laravel (PHP 8.2+ compatibility).

  2. Basic Detection:

    use Detection\MobileDetect;
    
    $detect = new MobileDetect();
    if ($detect->isMobile()) {
        // Mobile device logic
    }
    
  3. Laravel Integration: Bind the detector to the container in AppServiceProvider:

    public function register()
    {
        $this->app->singleton(MobileDetect::class, function () {
            return new MobileDetect();
        });
    }
    
  4. First Use Case: Redirect mobile users to a mobile-optimized URL:

    $detect = app(MobileDetect::class);
    if ($detect->isMobile()) {
        return redirect()->to('/mobile');
    }
    

Key Entry Points

  • isMobile(): Detects phones/tablets.
  • isTablet(): Subset of isMobile() for tablets.
  • is('device_type'): Check for specific devices (e.g., is('iPhone')).
  • features(): Returns an array of detected features (e.g., touch, retina).

Implementation Patterns

Workflows

1. Request-Based Detection (Laravel Middleware)

Create middleware to attach detection results to the request:

namespace App\Http\Middleware;

use Closure;
use Detection\MobileDetect;

class DetectMobileDevice
{
    public function handle($request, Closure $next)
    {
        $detect = new MobileDetect();
        $request->merge([
            'is_mobile' => $detect->isMobile(),
            'device_type' => $detect->getUserAgent(),
            'device_features' => $detect->features(),
        ]);
        return $next($request);
    }
}

Register in app/Http/Kernel.php:

protected $middleware = [
    \App\Http\Middleware\DetectMobileDevice::class,
];

2. Conditional View Logic

Use Blade directives to render mobile-specific views:

@if(request()->is_mobile)
    @include('mobile.layout')
@else
    @include('desktop.layout')
@endif

3. API Response Customization

Modify API responses based on device:

public function getData(Request $request)
{
    $response = [
        'data' => Model::all(),
        'meta' => [
            'mobile_optimized' => $request->is_mobile,
            'features' => $request->device_features,
        ],
    ];
    return response()->json($response);
}

4. Caching Detection Results

Leverage Laravel’s cache to avoid redundant detection:

$detect = app(MobileDetect::class);
$cacheKey = 'mobile_detect_' . md5($request->userAgent());
$isMobile = cache()->remember($cacheKey, now()->addHours(1), function () use ($detect) {
    return $detect->isMobile();
});

5. Feature Flagging

Disable heavy features on mobile:

if (!$request->is_mobile) {
    $data['advanced_chart'] = true;
}

Integration Tips

Laravel-Specific

  • Service Provider Binding: Extend the MobileDetect class and bind it to the container for reusable logic:

    $this->app->bind(MobileDetect::class, function () {
        $detect = new MobileDetect();
        $detect->setUserAgent(request()->userAgent());
        return $detect;
    });
    
  • Request Macros: Add helper methods to the Request class:

    Request::macro('isTablet', function () {
        return app(MobileDetect::class)->isTablet();
    });
    

Performance

  • Disable Auto-Initialization: If using custom headers (e.g., CloudFront), disable auto-initialization:

    $detect = new MobileDetect(['autoInitOfHttpHeaders' => false]);
    $detect->setUserAgent($userAgent);
    $detect->setHttpHeaders($headers);
    
  • Limit User-Agent Length: Reduce memory usage for long User-Agent strings:

    $detect = new MobileDetect(['maximumUserAgentLength' => 300]);
    

Testing

  • Mock Detection: Use Laravel’s testing helpers to mock mobile detection:
    $this->actingAsUser($user)
         ->withHeaders(['User-Agent' => 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X)'])
         ->get('/')
         ->assertSee('Mobile content');
    

Gotchas and Tips

Pitfalls

  1. User-Agent Spoofing:

    • Mobile detection relies on User-Agent strings, which can be spoofed. Combine with other signals (e.g., Sec-CH-UA-Mobile header) for higher accuracy:
      $detect->setHttpHeaders([
          'Sec-CH-UA-Mobile' => '?1', // Chrome's Client Hints
      ]);
      
  2. CloudFront/Proxy Headers:

    • If behind CloudFront, manually set headers:
      $detect = new MobileDetect(['autoInitOfHttpHeaders' => false]);
      $detect->setHttpHeaders([
          'CloudFront-Is-Mobile-Viewer' => 'true',
          'CloudFront-Is-Tablet-Viewer' => 'true',
      ]);
      
  3. Caching False Positives:

    • Cache detection results per user session, not globally, to avoid stale data:
      $cacheKey = 'mobile_detect_' . $request->ip() . '_' . $request->session()->getId();
      
  4. Tablet vs. Mobile Ambiguity:

    • isTablet() may return false for some tablets (e.g., older Android tablets). Use is('tablet') for broader matching:
      if ($detect->is('tablet') || $detect->isTablet()) {
          // Tablet logic
      }
      
  5. PHP 8.2+ Strict Types:

    • Ensure your Laravel app uses PHP 8.2+ for full compatibility. Older versions may trigger deprecation warnings.

Debugging

  1. Inspect User-Agent:

    • Log the raw User-Agent for debugging:
      \Log::debug('User-Agent:', [$detect->getUserAgent()]);
      
  2. Feature Detection:

    • Use features() to debug supported capabilities:
      \Log::debug('Device Features:', [$detect->features()]);
      
  3. Regex Overrides:

    • Override regex patterns for custom devices:
      $detect->setRegex('my_custom_device', '/MyCustomDevice/i');
      if ($detect->is('my_custom_device')) {
          // Custom logic
      }
      

Extension Points

  1. Custom Cache Backend:

    • Inject a PSR-16 cache (e.g., Laravel’s cache) for performance:
      use Detection\Cache\Cache;
      use Psr\SimpleCache\CacheInterface;
      
      $cache = new Cache(app(CacheInterface::class));
      $detect = new MobileDetect(['cache' => $cache]);
      
  2. Subclassing:

    • Extend MobileDetect for project-specific logic:
      class AppMobileDetect extends MobileDetect
      {
          public function isLegacyMobile()
          {
              return $this->isMobile() && $this->version('Android') < 5;
          }
      }
      
  3. Client Hints Support:

    • Use the Sec-CH-UA-Mobile header for modern browsers:
      $detect->setHttpHeaders([
          'Sec-CH-UA-Mobile' => $request->header('Sec-CH-UA-Mobile'),
      ]);
      
  4. Configuration:

    • Pass a config array to the constructor for fine-grained control:
      $detect = new MobileDetect([
          'autoInitOfHttpHeaders' => false,
          'maximumUserAgentLength' => 400,
          'cacheKeyFn' => fn($key) => sha1($key),
      ]);
      

Laravel-Specific Quirks

  1. Lumen Compatibility:

    • In Lumen, manually resolve the MobileDetect instance:
      $detect = new \Detection\MobileDetect();
      $detect->setUserAgent(request()->header('User-Agent'));
      
  2. Queue Jobs:

    • Avoid caching detection results in queue jobs (User-Agent may differ per request):
      // Bad: Cache globally
      // $isMobile = cache()->get('mobile_detect');
      
      // Good: Detect per job
      $detect = new MobileDetect();
      $detect->setUser
      
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope