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

digifa/mobile-detect-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require digifa/mobile-detect-bundle
    

    Ensure Digifa\MobileDetectBundle\MobileDetectBundle::class is registered in config/bundles.php.

  2. Configuration Publish the default config:

    php bin/console config:dump-reference DigifaMobileDetectBundle
    

    Override in config/packages/digifa_mobile_detect.yaml:

    digifa_mobile_detect:
        redirect_mobile: true
        mobile_url: '~mobile/'
        tablet_url: '~tablet/'
        desktop_url: '~desktop/'
    
  3. First Use Case Check if the current request is mobile in a controller:

    use Digifa\MobileDetectBundle\MobileDetect;
    
    public function index(MobileDetect $detect)
    {
        if ($detect->isMobile()) {
            return $this->redirectToRoute('mobile_home');
        }
        // Desktop logic
    }
    

Implementation Patterns

Core Workflows

  1. Automatic Redirects Enable via redirect_mobile: true in config. The bundle hooks into Symfony’s event system (kernel.request) to redirect before rendering templates.

  2. Conditional Rendering Use the MobileDetect service in Twig:

    {% if app.service('digifa_mobile_detect').isMobile() %}
        {# Mobile-specific content #}
    {% endif %}
    
  3. Custom Detection Logic Extend the default detection by overriding the service:

    # config/services.yaml
    services:
        Digifa\MobileDetectBundle\MobileDetect:
            arguments:
                $userAgent: '%kernel.user_agent%'
                $mobileRegex: '~your_custom_regex~'
    
  4. Route-Based Mobile Views Use route parameters or annotations to serve mobile/tablet-specific routes:

    #[Route('/product/{id}', name: 'product_desktop')]
    public function productDesktop(Product $product) { ... }
    
    #[Route('/mobile/product/{id}', name: 'product_mobile')]
    public function productMobile(Product $product) { ... }
    

    Redirect logic in a base controller:

    public function __construct(private MobileDetect $detect) {}
    
    public function preflight(Request $request)
    {
        if ($this->detect->isMobile() && $request->getPathInfo() !== '/mobile/') {
            return $this->redirectToRoute('product_mobile', ['id' => $request->attributes->get('id')]);
        }
    }
    
  5. A/B Testing or Feature Flags Combine with Symfony’s Feature component to toggle mobile-specific features:

    if ($detect->isMobile() && Feature::isEnabled('mobile_feature')) {
        // Enable mobile-only feature
    }
    

Gotchas and Tips

Pitfalls

  1. Caching Headers

    • Mobile redirects may break cached responses. Exclude mobile routes from HTTP caching:
      # config/packages/framework.yaml
      framework:
          http_cache:
              invalidation:
                  exclude_paths: ['^/mobile/', '^/tablet/']
      
  2. User-Agent Spoofing

    • Mobile detection relies on User-Agent strings, which can be spoofed. Validate with additional checks (e.g., screen width via JavaScript) if security is critical.
  3. Route Conflicts

    • Ensure mobile/tablet routes don’t conflict with desktop routes. Use prefixes (e.g., /mobile/, /tablet/) or subdomains (m.yourdomain.com).
  4. Performance Overhead

    • Regex-based detection adds minimal overhead (~1ms), but avoid running it on every request if unused. Lazy-load the service:
      $detect = app()->has('digifa_mobile_detect') ? app('digifa_mobile_detect') : null;
      

Debugging

  1. Log Detection Results Add a debug endpoint to inspect detection:

    #[Route('/_debug/mobile-detect')]
    public function debugMobileDetect(MobileDetect $detect): JsonResponse
    {
        return new JsonResponse([
            'isMobile' => $detect->isMobile(),
            'isTablet' => $detect->isTablet(),
            'userAgent' => $detect->getUserAgent(),
        ]);
    }
    
  2. Override Detection Logic For testing, mock the MobileDetect service:

    // tests/ControllerTest.php
    protected function getMobileDetectMock(bool $isMobile = true): MobileDetect
    {
        $mock = $this->createMock(MobileDetect::class);
        $mock->method('isMobile')->willReturn($isMobile);
        return $mock;
    }
    

Extension Points

  1. Custom Device Lists Extend the bundle’s device database by overriding the MobileDetect service and injecting a custom Mobile_Detect_Lib instance:

    // src/Service/CustomMobileDetect.php
    use Mobile_Detect_Lib;
    
    class CustomMobileDetect extends MobileDetect
    {
        public function __construct()
        {
            $detect = new Mobile_Detect_Lib();
            $detect->setUserAgent($_SERVER['HTTP_USER_AGENT']);
            $this->setDetect($detect);
            // Add custom device patterns
            $detect->setCustomPatterns(['custom_pattern' => '~custom_regex~']);
        }
    }
    
  2. Event-Based Redirects Listen to the mobile_detect.redirect event to customize redirects:

    // src/EventListener/MobileRedirectListener.php
    use Digifa\MobileDetectBundle\Event\RedirectEvent;
    
    class MobileRedirectListener
    {
        public function onRedirect(RedirectEvent $event)
        {
            if ($event->isMobile() && $event->getRequest()->getPathInfo() === '/admin') {
                $event->setRedirectUrl('/desktop/admin');
            }
        }
    }
    

    Register in services.yaml:

    services:
        App\EventListener\MobileRedirectListener:
            tags:
                - { name: 'kernel.event_listener', event: 'mobile_detect.redirect', method: 'onRedirect' }
    
  3. Tablet-Specific Logic Use isTablet() to target tablets explicitly:

    if ($detect->isTablet()) {
        $this->addFlash('tablet', 'Optimized for tablets!');
    }
    

Configuration Quirks

  1. URL Formats

    • mobile_url and tablet_url support Symfony’s router placeholders (e.g., ~mobile/{path}). Ensure trailing slashes match your routing conventions.
  2. Case Sensitivity

    • Regex patterns in mobile_regex are case-sensitive. Use (?i) for case-insensitive matching:
      digifa_mobile_detect:
          mobile_regex: '~(?i)mobile~'
      
  3. Environment-Specific Rules Disable redirects in dev environments:

    # config/packages/dev/digifa_mobile_detect.yaml
    digifa_mobile_detect:
        redirect_mobile: false
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui