laravel-localized-routes
laravel-localized-routes copied to clipboard
* Use Localizer to Detect and Set the Locale
Hello!
I have added the following languages: 'supported-locales' => ['en', 'uk'], 'redirect_to_localized_urls' => true, 'use_localizer' => true,
.
How can I redirect from index to site.com/uk/
OR site.com/en/
?
<?php
use Illuminate\Support\Facades\Route;
Route::fallback(\CodeZero\LocalizedRoutes\Controller\FallbackController::class)
->middleware(\CodeZero\LocalizedRoutes\Middleware\SetLocale::class);
Route::localized(function () {
Route::get('/', function () {
return view('welcome');
});
});
And is it possible to make an automatic redirect with HTTP_ACCEPT_LANGUAGE header preemption?
Hi,
You can add the middleware to the index route to get a locale from the session or cookie or the browser. Then I just do a redirect to a localized route:
// Routes
Route::get('/', [HomeController::class, 'redirect'])->name('index')->middleware(\CodeZero\LocalizedRoutes\Middleware\SetLocale::class);
Route::localized(function () {
Route::get('/', [HomeController::class, 'home'])->name('home');
});
// HomeController
public function redirect()
{
return redirect()->route('home');
}
public function home()
{
return view('home');
}
For the browser detection I'm using https://github.com/codezero-be/browser-locale. By default it will spit out something like this:
$browser = new \CodeZero\BrowserLocale\BrowserLocale('en-US,nl;q=0.8');
$filter = \CodeZero\BrowserLocale\Filters\CombinedFilter;
$locales = $browser->filter($filter);
//=> Result: ['en-US', 'en', 'nl']
So probably 'en' and 'en-UK' for you.
This list will be checked by https://github.com/codezero-be/laravel-localizer against the supported locales for a match.
You can create a new BrowserDetector that uses a different BrowserLocale Filter or some custom logic. This is the default one:
https://github.com/codezero-be/laravel-localizer/blob/master/src/Detectors/BrowserDetector.php
To actually use it you need to publish the Localized config file in your project and add the new class to the detectors array.
https://github.com/codezero-be/laravel-localizer/blob/master/config/localizer.php
You may even want to create 2 detectors, a CountryDetector and a LanguageDetector and add them to the config in order of priority. Only the first match is used. There are also 2 BrowserLocale Filters for that.