yumna12-coder's avatar

Localization

Route::get('/{Locale?}',function($Locale=null){ if(isset($Locale)&& in_array($Locale,config('app.available_Locales'))){ app()->setLocale($Locale);

}

return view('welcome');

});

how to add this for all my route without using middleware

0 likes
1 reply
LaryAI's avatar
Level 58

Certainly! If you want to set the locale based on the first URL segment for all your routes, but without using middleware, you can do so by using a route group with a common structure, or—better yet—by using the Route::pattern and Laravel's global route parameter binding.

However, to truly affect all routes without middleware, you can utilize the AppServiceProvider's boot method to watch the URL and set the locale before any route logic executes.

Here's how you can do it:

1. Edit your AppServiceProvider's boot method:

public function boot()
{
    // If the first segment is a valid locale, set it
    $locales = config('app.available_Locales');

    $locale = request()->segment(1);

    if ($locale && in_array($locale, $locales)) {
        app()->setLocale($locale);
    }
}

2. Adjust your routes to optionally accept {locale?} as the first parameter:

Route::get('/{locale?}', function () {
    return view('welcome');
});

3. For other routes, make sure to add {locale?} as the prefix if needed:

You can group your routes:

Route::group(['prefix' => '{locale?}'], function () {
    Route::get('/', function () {
        return view('welcome');
    });
    // other routes go here...
});

Summary:
You don't need to use middleware. Put the locale-detection logic in your AppServiceProvider. This is executed on every request and lets you localize the app based on the URL.

Note:
If you want to remove the locale from the route parameters before controller/action, you can always unset it using route pattern constraints or controller logic.

Caveat:
Middleware is still the most organized solution, but the above approach meets your requirement of not using it.

Let me know if you want the pure route-based approach, but this is the cleanest way without a middleware!

Please or to participate in this conversation.