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

Trans Routing Bundle Laravel Package

aaronadal/trans-routing-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require aaronadal/trans-routing-bundle
    

    Register the bundle in config/bundles.php (Symfony) or config/app.php (Laravel via Symfony bridge):

    return [
        // ...
        Aaronadal\TransRoutingBundle\AaronadalTransRoutingBundle::class => ['all' => true],
    ];
    
  2. Configuration Define locales in config/packages/aaronadal_trans_routing.yaml (Symfony) or config/trans_routing.php (Laravel):

    locales: [en, fr, es]
    default_locale: en
    
  3. First Use Case Annotate a route with @TransRouting in a Symfony controller:

    use Aaronadal\TransRoutingBundle\Annotation\TransRouting;
    
    /**
     * @Route("/{_locale}/home", name="home")
     * @TransRouting(locales={"en": "home", "fr": "accueil"})
     */
    public function homeAction(Request $request, string $_locale) { ... }
    

    Laravel Alternative: Use route model binding or middleware to inject _locale and map translations in routes/web.php:

    Route::get('/{locale}/home', [HomeController::class, 'index'])
        ->where('locale', implode('|', config('trans_routing.locales')))
        ->middleware('locale');
    

Implementation Patterns

Core Workflow

  1. Route Translation Mapping

    • Use @TransRouting (Symfony) or route groups (Laravel) to define locale-specific route names.
    • Example (Symfony):
      # config/routes/trans_routes.yaml
      home:
          path: /{_locale}/home
          defaults: { _controller: App\Controller\HomeController::home }
          requirements:
              _locale: en|fr|es
          trans_routing:
              en: home_en
              fr: accueil
              es: inicio
      
  2. Locale Detection

    • Leverage Symfony’s RequestStack or Laravel’s AppServiceProvider to auto-detect locale from:
      • URL parameter ({_locale}).
      • Session (app()->getLocale()).
      • Header (Accept-Language).
    • Example (Laravel middleware):
      public function handle($request, Closure $next) {
          $locale = $request->route('_locale') ?? session('locale') ?? config('app.locale');
          app()->setLocale($locale);
          return $next($request);
      }
      
  3. Dynamic Route Generation

    • Use the bundle’s TransRouter service (Symfony) or a custom helper (Laravel) to generate locale-aware URLs:
      // Laravel: Add to AppServiceProvider
      $router = new \Aaronadal\TransRoutingBundle\Router\TransRouter($this->app['router']);
      $router->setLocales(config('trans_routing.locales'));
      
      // Generate URL
      route('home', ['_locale' => 'fr']); // /fr/accueil
      
  4. Fallback Logic

    • Configure fallback locales in config/trans_routing.php:
      'fallback_locale' => 'en',
      'fallback_routes' => [
          'fr' => 'en', // Redirect fr/* to en/* if no translation exists
      ],
      

Gotchas and Tips

Pitfalls

  1. Locale Parameter Conflicts

    • Ensure {_locale} doesn’t clash with other route parameters. Use underscores or reserved namespaces.
    • Fix: Rename to {lang} or {l} if needed, and update middleware/config accordingly.
  2. Caching Issues

    • Symfony’s router cache may not reflect changes to @TransRouting annotations immediately.
    • Fix: Clear cache after updates:
      php bin/console cache:clear
      
    • Laravel: Use php artisan route:clear or php artisan config:clear.
  3. Missing Translations

    • If a locale lacks a translation, the bundle defaults to the default_locale. Test edge cases:
      // Laravel: Add to AppServiceProvider
      $this->app->afterResolving('router', function ($router) {
          $router->missing(function ($request) {
              return redirect()->route('home', ['_locale' => config('trans_routing.default_locale')]);
          });
      });
      
  4. Case Sensitivity

    • Route names in @TransRouting are case-sensitive. Use consistent casing (e.g., home vs. Home).

Debugging Tips

  1. Dump Route Collection

    • Symfony:
      $router->getRouteCollection()->get('home')->getPath();
      
    • Laravel:
      dd(Route::getRoutes()->getByName('home')->uri());
      
  2. Log Locale Resolution

    • Add a listener to log locale detection:
      // Symfony EventSubscriber
      public function onKernelRequest(GetResponseEvent $event) {
          $request = $event->getRequest();
          $this->logger->info('Locale resolved:', ['locale' => $request->get('_locale')]);
      }
      
  3. Test Locale-Specific Routes

    • Use PHPUnit to test route generation for each locale:
      public function testLocaleRoutes() {
          foreach (config('trans_routing.locales') as $locale) {
              $url = route('home', ['_locale' => $locale]);
              $this->assertStringContainsString($locale, $url);
          }
      }
      

Extension Points

  1. Custom Route Translator

    • Extend the bundle’s TransRouter to add logic (e.g., SEO-friendly slugs):
      class CustomTransRouter extends \Aaronadal\TransRoutingBundle\Router\TransRouter {
          public function generate($name, $parameters = [], $absolute = false) {
              $parameters['_locale'] = $this->generateSlug($parameters['_locale']);
              return parent::generate($name, $parameters, $absolute);
          }
      }
      
    • Bind it in services.yaml (Symfony) or AppServiceProvider (Laravel).
  2. Database-Backed Translations

    • Store route translations in a route_translations table and fetch them dynamically:
      // Laravel: Add to TransRouter
      public function getTranslatedName($name, $locale) {
          return DB::table('route_translations')
              ->where('route_name', $name)
              ->where('locale', $locale)
              ->value('translated_name') ?? $name;
      }
      
  3. API Integration

    • Expose an API endpoint to fetch locale-specific routes:
      Route::get('/api/routes', function () {
          return collect(config('trans_routing.locales'))
              ->mapWithKeys(fn($locale) => [
                  $locale => route('home', ['_locale' => $locale])
              ]);
      });
      
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.
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
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