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

I18N Routing Bundle Laravel Package

alvadi-it/i18n-routing-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require alvadi-it/i18n-routing-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Alvadi\I18nRoutingBundle\AlvadiI18nRoutingBundle::class => ['all' => true],
    ];
    
  2. Configure Supported Locales In config/packages/alvadi_i18n_routing.yaml:

    alvadi_i18n_routing:
        locales: ['en', 'fr', 'de']
        default_locale: 'en'
        prefix_locale: true  # e.g., `/en/about`
    
  3. First Route Definition In config/routes.yaml:

    app_home:
        path: /{_locale}/about
        controller: App\Controller\HomeController::about
        requirements:
            _locale: en|fr|de
    
  4. Generate URLs with Locale

    $url = $this->generateUrl('app_home', ['_locale' => 'fr']);
    // Outputs: /fr/about
    
  5. Detect Current Locale

    $locale = $this->get('router')->getContext()->getParameter('_locale');
    

Implementation Patterns

Common Workflows

1. Locale-Aware Routing

  • Prefixing Locales: Use prefix_locale: true to enforce /{locale}/ structure.
  • Hidden Locale Parameter: Use _locale in route requirements for flexibility:
    app_blog_post:
        path: /blog/{slug}
        controller: App\Controller\BlogController::show
        requirements:
            _locale: en|fr
            slug: '.*'
    

2. Dynamic Locale Switching

  • Middleware for Locale Detection: Create a middleware to auto-detect locale from:
    • Subdomain (fr.example.comfr)
    • URL path (/fr/about)
    • Session/cookie fallback
    // src/Kernel.php
    protected function build(RequestContext $context): void
    {
        $locale = $this->detectLocale(); // Custom logic
        $context->setParameter('_locale', $locale);
    }
    

3. Locale-Specific Routes

  • Route Overrides: Define locale-specific routes in YAML:
    app_home_fr:
        path: /accueil
        controller: App\Controller\HomeController::about
        defaults: { _locale: 'fr' }
        requirements:
            _locale: fr
    

4. Integration with Symfony UX

  • Live Components + Locale Switcher:
    // src/Components/LocaleSwitcher.php
    use Alvadi\I18nRoutingBundle\Routing\RouterInterface;
    
    public function __construct(private RouterInterface $router) {}
    
    public function render(): string {
        $locales = ['en', 'fr', 'de'];
        $current = $this->router->getContext()->getParameter('_locale');
        return $this->renderView('locale_switcher.html.twig', [
            'locales' => $locales,
            'current' => $current,
        ]);
    }
    

5. API Locale Handling

  • Header-Based Locale: Override RequestContext to read Accept-Language:
    # config/packages/alvadi_i18n_routing.yaml
    alvadi_i18n_routing:
         locale_from_header: true
    

Integration Tips

With FOSUserBundle

  • Locale-Persistent Login: Store locale in user entity and hydrate RequestContext post-login:
    // src/EventListener/LoginListener.php
    public function onSecurityInteractiveLogin(InteractiveLoginEvent $event) {
        $user = $event->getAuthenticationToken()->getUser();
        $context = $this->router->getContext();
        $context->setParameter('_locale', $user->getPreferredLocale());
    }
    

With API Platform

  • Locale in URL + Headers: Combine path and header-based locale:
    alvadi_i18n_routing:
        locale_from_header: true
        prefix_locale: false
    
    Route:
    api_posts:
        path: /posts/{id}
        methods: [GET]
        requirements:
            _locale: en|fr
    

With Doctrine

  • Locale-Aware Entities: Use locale field in entities and filter queries:
    // src/Repository/PostRepository.php
    public function findByLocale(string $locale): array {
        return $this->createQueryBuilder('p')
            ->where('p.locale = :locale')
            ->setParameter('locale', $locale)
            ->getQuery()
            ->getResult();
    }
    

Gotchas and Tips

Pitfalls

1. Locale Parameter Conflicts

  • Issue: _locale clashes with route parameters (e.g., /en/{id} where id is en).
  • Fix: Use prefix_locale: true or rename the parameter (e.g., _lang).

2. Caching Headaches

  • Issue: Symfony’s router cache may not invalidate when locales are added/removed.
  • Fix: Clear cache after changing locales config:
    php bin/console cache:clear
    

3. Default Locale Fallback

  • Issue: Missing locale redirects to default_locale, but the URL may break.
  • Fix: Use a RouteListener to rewrite URLs:
    // src/EventListener/LocaleFallbackListener.php
    public function onKernelRequest(GetResponseEvent $event) {
        $request = $event->getRequest();
        if (!$request->hasPreviousSession() && $request->get('_locale') !== $this->defaultLocale) {
            $request->attributes->set('_locale', $this->defaultLocale);
            $request->query->set('_locale', $this->defaultLocale);
        }
    }
    

4. Case Sensitivity

  • Issue: Locale codes in URLs are case-sensitive (/FR//fr/).
  • Fix: Normalize in middleware:
    $locale = strtolower($request->get('_locale'));
    

5. Nested Routes

  • Issue: Child routes may inherit parent locale incorrectly.
  • Fix: Explicitly set _locale in nested routes or use _locale in all route requirements.

Debugging Tips

1. Dump Router Context

dump($this->get('router')->getContext()->getParameters());

Outputs:

array:_locale => 'fr', _route => 'app_home', ...

2. Check Route Requirements

Validate locale requirements in routes:

app_test:
    path: /{_locale}/test
    requirements:
        _locale: 'en|fr|de'  # Explicitly list allowed locales

3. Log Locale Detection

Add a listener to log locale sources:

// src/EventListener/LocaleDebugListener.php
public function onKernelRequest(GetResponseEvent $event) {
    $request = $event->getRequest();
    $this->logger->info('Locale detected from:', [
        'path' => $request->get('_locale'),
        'header' => $request->headers->get('Accept-Language'),
        'session' => $request->getSession()->get('_locale'),
    ]);
}

Extension Points

1. Custom Locale Provider

Implement Alvadi\I18nRoutingBundle\Locale\LocaleProviderInterface:

class CustomLocaleProvider implements LocaleProviderInterface {
    public function getLocale(Request $request): string {
        // Custom logic (e.g., geoIP, user agent)
        return 'en';
    }
}

Register in config:

alvadi_i18n_routing:
    locale_provider: App\Service\CustomLocaleProvider

2. Dynamic Locale Routes

Use a compiler pass to generate locale-specific routes at runtime:

// src/DependencyInjection/Compiler/LocaleRoutePass.php
public function process(ContainerBuilder $container) {
    $definition = $container->findDefinition('router');
    $definition->addMethodCall('addLocaleRoutes', [
        $container->getParameter('alvadi_i18n_routing.locales'),
    ]);
}

3. Locale-Aware Redirects

Extend the bundle’s UrlGenerator to handle redirects:

// src/Service/LocaleAwareUrlGenerator.php
public function generate(string $route, array $parameters = [], int $referenceType = self::ABSOLUTE_PATH): string {
    if (!isset($parameters['_locale'])) {
        $parameters['
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.
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
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver