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

Mobile Detect Bundle Laravel Package

suncat/mobile-detect-bundle

Symfony bundle integrating Mobile_Detect to identify phones/tablets by user agent, manage device-specific views (mobile/tablet/full), and optionally redirect users to mobile or tablet versions of your site. Supports Symfony 2.4–4.0.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require suncat/mobile-detect-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Suncat\MobileDetectBundle\SuncatMobileDetectBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config:

    php bin/console config:dump-reference SuncatMobileDetectBundle
    

    Or override in config/packages/suncat_mobile_detect.yaml:

    suncat_mobile_detect:
        mobile_view: 'mobile'       # 'mobile', 'tablet', or 'full'
        redirect:
            mobile: ~                # URL or false to disable
            tablet: ~                # URL or false to disable
        user_agent: ~                # Custom User-Agent string (optional)
    
  3. First Use Case Detect device type in a controller:

    use Suncat\MobileDetectBundle\MobileDetect;
    
    public function index(MobileDetect $detect)
    {
        $deviceType = $detect->getDeviceType(); // 'mobile', 'tablet', or 'desktop'
        $isMobile = $detect->isMobile();
        $isTablet = $detect->isTablet();
    
        return $this->render("page/{$deviceType}_view.html.twig");
    }
    

Implementation Patterns

Core Workflows

  1. Device Detection in Controllers Inject MobileDetect service to dynamically adjust responses:

    public function show(MobileDetect $detect, Request $request)
    {
        if ($detect->isMobile() && $detect->is('iPhone')) {
            return $this->redirectToRoute('mobile_optimized_route');
        }
        return $this->render('default_template.html.twig');
    }
    
  2. Twig Integration Use the mobile_detect Twig extension:

    {% if mobile_detect.isMobile() %}
        <link rel="stylesheet" href="{{ asset('css/mobile.css') }}">
    {% endif %}
    
  3. Redirect Management Configure redirects in config/packages/suncat_mobile_detect.yaml:

    redirect:
        mobile: 'https://m.example.com'
        tablet: 'https://tablet.example.com'
    

    Trigger redirects via event listener (optional):

    use Suncat\MobileDetectBundle\Event\MobileDetectEvent;
    
    public function onMobileDetect(MobileDetectEvent $event)
    {
        if ($event->isMobile() && $event->getRedirectUrl()) {
            $event->setRedirect(true);
        }
    }
    
  4. Custom Device Checks Extend detection logic:

    $detect->is('iPad'); // Checks for iPad specifically
    $detect->is('Android'); // Checks for Android OS
    $detect->isTablet(); // Checks for any tablet
    

Integration Tips

  • Routing: Use Symfony’s RequestContext to dynamically set _format or _locale based on device type.
  • Caching: Cache device detection results if performance is critical (e.g., in a high-traffic API).
  • Testing: Mock MobileDetect in PHPUnit:
    $detect = $this->createMock(MobileDetect::class);
    $detect->method('isMobile')->willReturn(true);
    $this->container->set('mobile_detect', $detect);
    

Gotchas and Tips

Common Pitfalls

  1. User-Agent Overrides

    • If testing locally, ensure your User-Agent header matches the device you’re testing. Use browser extensions (e.g., "User-Agent Switcher") or tools like curl:
      curl -A "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2 like Mac OS X)" http://example.com
      
  2. Redirect Loops

    • Disable redirects during development (redirect: { mobile: false, tablet: false }) to avoid infinite loops when testing.
  3. False Positives/Negatives

    • Some devices (e.g., Chromebooks) may not be classified correctly. Use is() for granular checks:
      if ($detect->is('Android') && !$detect->is('Tablet')) {
          // Handle Android phones specifically
      }
      
  4. Configuration Conflicts

    • Ensure mobile_view and redirect settings align with your routing (e.g., if mobile_view: 'mobile' but no mobile route exists, requests will 404).

Debugging

  • Log Device Info Dump detection results for debugging:

    $detect->getUserAgent();
    $detect->getDeviceName();
    $detect->getOsName();
    $detect->getVersion();
    
  • Check Events Listen to mobile_detect events to debug redirect logic:

    # config/services.yaml
    Suncat\MobileDetectBundle\EventListener\MobileDetectListener:
        tags:
            - { name: kernel.event_listener, event: mobile_detect, method: onMobileDetect }
    

Extension Points

  1. Custom Device Rules Extend the MobileDetect class or override the service:

    # config/services.yaml
    Suncat\MobileDetectBundle\MobileDetect:
        arguments:
            - '@service_container' # Pass custom dependencies
        calls:
            - [setCustomRules, ['%kernel.project_dir%/config/mobile_rules.php']]
    
  2. Event Subscribers Subscribe to mobile_detect events for custom logic:

    use Suncat\MobileDetectBundle\Event\MobileDetectEvent;
    
    class CustomMobileSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                MobileDetectEvent::NAME => 'onMobileDetect',
            ];
        }
    
        public function onMobileDetect(MobileDetectEvent $event)
        {
            if ($event->isMobile() && $event->getDeviceName() === 'iPhone') {
                $event->setData(['ios_version' => $event->getVersion()]);
            }
        }
    }
    
  3. Override Templates Create device-specific templates in templates/page/:

    templates/
        page/
            mobile_view.html.twig
            tablet_view.html.twig
            full_view.html.twig
    

Configuration Quirks

  • Case Sensitivity: Device names in is() are case-sensitive (e.g., is('iPhone') vs. is('iphone')).
  • Default View: If mobile_view is not set, defaults to 'full' (desktop view).
  • Redirect Priority: Redirects take precedence over mobile_view if both are configured.

Performance Notes

  • Heavy Traffic: Device detection adds minimal overhead (~1-2ms per request). For APIs, cache results in the Request object if reused.
  • User-Agent Parsing: The underlying Mobile_Detect library is optimized, but avoid calling is() repeatedly in loops.
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.
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php
trappistes/laravel-custom-fields
splash/sonata-admin
splash/metadata