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

Localized Routes Laravel Package

braunstetter/localized-routes

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require braunstetter/localized-routes
    

    Add the bundle to config/bundles.php (Symfony) or register the service provider in config/app.php (Laravel):

    // Laravel (if using a custom provider)
    Braunstetter\LocalizedRoutesBundle\LocalizedRoutesServiceProvider::class,
    
  2. Configure Routes: Update routes/web.php to include the locale prefix in your route definitions:

    Route::prefix('{_locale}')->group(function () {
        Route::get('/', 'HomeController@index');
    });
    

    Ensure _locale is defined in your middleware (e.g., app/Http/Middleware/SetLocale.php).

  3. Middleware Setup: Add the LocalizedRoutesMiddleware to your HTTP kernel (e.g., app/Http/Kernel.php):

    protected $middlewareGroups = [
        'web' => [
            // ...
            \Braunstetter\LocalizedRoutesBundle\Http\Middleware\LocalizedRoutesMiddleware::class,
        ],
    ];
    
  4. First Use Case: Access /en/home (or your default locale) to test. The middleware will redirect /home to /en/home if the locale is en.


Implementation Patterns

Workflows

  1. Locale Detection:

    • Use middleware to detect the locale (e.g., from session, cookie, or URL subdomain).
    • Example middleware (app/Http/Middleware/SetLocale.php):
      public function handle($request, Closure $next) {
          $locale = $request->segment(1) ?? config('app.locale');
          app()->setLocale($locale);
          return $next($request);
      }
      
  2. Route Grouping:

    • Group all localized routes under {_locale} prefix:
      Route::prefix('{_locale}')->middleware('locale')->group(function () {
          Route::get('/news', 'NewsController@index');
          Route::resource('posts', 'PostController');
      });
      
    • Exclude specific routes (e.g., login) by omitting the prefix:
      Route::middleware('guest')->group(function () {
          Route::get('/login', 'AuthController@login');
      });
      
  3. Dynamic Locale Switching:

    • Add a locale switcher link in your layout:
      @foreach(config('app.locales') as $locale)
          <a href="{{ url()->current(), str_replace(url()->current(), '', $locale) }}">
              {{ $locale }}
          </a>
      @endforeach
      
  4. API Localization:

    • Apply the same prefix to API routes:
      Route::prefix('{_locale}')->middleware('api', 'locale')->group(function () {
          Route::apiResource('posts', 'PostController');
      });
      

Integration Tips

  • Laravel Localization: Combine with laravel-localization for seamless locale switching and URL generation:

    use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
    LaravelLocalization::setLocale();
    
  • Route Caching: Disable route caching during development if locales are dynamic:

    Route::getCache()->forever();
    
  • Fallback Locales: Configure fallback locales in config/app.php:

    'fallback_locales' => ['en', 'de'],
    

Gotchas and Tips

Pitfalls

  1. Locale Conflict:

    • If _locale is also a valid route parameter (e.g., /posts/{_locale}), the middleware may misinterpret it. Solution: Use a unique placeholder like {_lang}:
      Route::prefix('{_lang}')->group(...);
      
  2. Redirect Loops:

    • Ensure the LocalizedRoutesMiddleware runs before other middleware that might modify the request (e.g., VerifyCsrfToken). Solution: Order middleware correctly in Kernel.php.
  3. Case Sensitivity:

    • Locale codes (e.g., EN vs. en) may cause issues. Solution: Normalize locales in middleware:
      $locale = strtolower($request->segment(1));
      
  4. Caching Issues:

    • Aggressive route caching (e.g., php artisan route:cache) may break dynamic locales. Solution: Clear cache after locale changes:
      php artisan route:clear
      

Debugging

  • Check Middleware Order: Use php artisan route:list to verify routes are prefixed correctly. Missing prefixes often indicate middleware misconfiguration.

  • Log Locale Detection: Add debug logs in LocalizedRoutesMiddleware:

    \Log::debug('Detected locale:', [$request->segment(1)]);
    
  • Test Redirects: Use php artisan route:debug to trace redirects and ensure no infinite loops.

Extension Points

  1. Custom Locale Sources: Override the default locale detection logic by extending the middleware:

    class CustomLocalizedRoutesMiddleware extends LocalizedRoutesMiddleware {
        protected function getLocaleFromRequest(Request $request) {
            return $request->cookie('locale') ?? parent::getLocaleFromRequest($request);
        }
    }
    
  2. Exclude Routes: Skip localization for specific routes by adding a skip_localization flag:

    Route::get('/health', 'HealthController@check')->middleware('skip_localization');
    

    Extend the middleware to check for this flag.

  3. Subdomain Support: Integrate with laravel-localization for subdomain-based locales (e.g., en.example.com):

    Route::prefix('{_locale}')->domain(['{locale}.example.com'])->group(...);
    
  4. Fallback Logic: Customize fallback behavior in the middleware:

    protected function getFallbackLocale($locale) {
        return config('app.fallback_locales')[0] ?? config('app.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.
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