Search code examples
phplaravellocalizationlaravel-10laravel-localization

Using a different domain for each language in Laravel


I am building a website in Laravel and need to use a different domain for each language. Currently I'm using mcamara/laravel-localization for the localization. For example:

  • EN => my-english-website.com
  • NL => my-dutch-website.com

It seems like using different domains is not something that is supported by default. Has someone run into this issue and knows how to solve this?


Solution

  • Subdomains are supported by default.

    Route::domain('{locale}.website.com')->middleware('set-locale')->group(function () {
        // your routes here
    })->where('locale', '(my-english|my-dutch|my-spanish)');
    

    You use where to match the {locale} parameter to a regex pattern and then use a middleware to actually set the locale.

    Maybe you'd have something like this in the middleware

    public function handle(Request $request, Closure $next)
    {
        $locales = ['my-english' => 'en', 'my-spanish' => 'es', ...];
    
        app()->setLocale($locales[$this->route->parameter('locale')]);
    
        return $next($request);
    }
    

    I'm not sure if this was the correct syntax, but you get the idea.