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

cpoint-eu/mobile-detect-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require cpoint-eu/mobile-detect-bundle
    

    Add to config/bundles.php (Symfony 5+ auto-discovers, but verify):

    return [
        // ...
        CpointEu\MobileDetectBundle\CpointEuMobileDetectBundle::class => ['all' => true],
    ];
    
  2. Basic Detection Inject the service in a controller:

    use CpointEu\MobileDetectBundle\Service\MobileDetectService;
    
    public function index(MobileDetectService $detectService)
    {
        $isMobile = $detectService->isMobile();
        $deviceType = $detectService->getDeviceType(); // 'mobile', 'tablet', or 'desktop'
        // ...
    }
    
  3. First Use Case: Conditional Rendering

    {% if app.request.attributes.get('_mobile') %}
        {# Load mobile-specific template #}
        {{ include('mobile/home.html.twig') }}
    {% else %}
        {# Default desktop template #}
        {{ include('desktop/home.html.twig') }}
    {% endif %}
    

Implementation Patterns

Workflow: Redirect to Mobile Site

  1. Configure Routes Define mobile routes in config/routes/mobile.yaml:

    mobile_homepage:
        path: /m
        controller: App\Controller\MobileController::index
    
  2. Middleware for Redirects Create a custom middleware (src/Middleware/MobileRedirect.php):

    public function handle(Request $request, Closure $next)
    {
        if ($this->mobileDetect->isMobile() && !$request->isRequestFromMobileRoute()) {
            return redirect()->to('/m');
        }
        return $next($request);
    }
    

    Register in config/kernel.php:

    protected function build(RequestContext $requestContext): void
    {
        $this->add(MobileRedirect::class);
    }
    

Integration with Twig

  • Global Variables The bundle auto-registers mobile (bool) and device_type (string) in Twig:

    {{ dump(app.request.attributes.get('_mobile')) }} {# true/false #}
    
  • Custom Logic Extend the service for app-specific checks:

    public function isMobileApp(): bool
    {
        return $this->isMobile() && $this->isTablet() === false;
    }
    

API-Specific Use Cases

  • Conditional API Responses
    public function getData(MobileDetectService $detect)
    {
        return response()->json([
            'data' => $detect->isMobile()
                ? $this->mobileDataProvider->get()
                : $this->desktopDataProvider->get(),
        ]);
    }
    

Gotchas and Tips

Pitfalls

  1. False Positives

    • Tablets may be misclassified as mobile. Override detection:
      $this->mobileDetect->setTabletUserAgent('CustomTabletUA');
      
  2. Caching Issues

    • Disable caching for mobile detection routes if using Varnish/Nginx:
      # config/packages/framework.yaml
      framework:
          router:
              default_context:
                  mobile: false  # Disable auto-detection in cache
      
  3. Route Conflicts

    • Ensure mobile routes (/m) don’t clash with existing paths. Use:
      mobile_routes:
          resource: "@MobileDetectBundle/Resources/config/routing.yml"
          prefix: /mobile
      

Debugging

  • Log Device Info

    $this->mobileDetect->getUserAgent(); // Raw UA string
    $this->mobileDetect->getDeviceInfo(); // Array with all detected features
    
  • Test with Headers Simulate mobile UAs in tests:

    $client->setServerParameter('HTTP_USER_AGENT', 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2)');
    

Extension Points

  1. Custom Device Types Extend the service:

    public function isWearable(): bool
    {
        return $this->isMobile() && str_contains($this->getUserAgent(), 'Watch');
    }
    
  2. Event Listeners Trigger actions on mobile detection:

    // src/EventListener/MobileListener.php
    public function onKernelRequest(GetResponseEvent $event)
    {
        if ($this->mobileDetect->isMobile()) {
            $event->setResponse(new Response('Mobile content'));
        }
    }
    

    Register in services.yaml:

    services:
        App\EventListener\MobileListener:
            tags:
                - { name: kernel.event_listener, event: kernel.request }
    
  3. Configuration Overrides Override default settings in config/packages/cpoint_eu_mobile_detect.yaml:

    cpoint_eu_mobile_detect:
        mobile_user_agents:
            - 'Android'
            - 'iPhone'
        tablet_user_agents:
            - 'iPad'
        desktop_user_agents:
            - 'Macintosh'
    
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