DominikN.
DominikN.

Reputation: 1245

Laravel default locale not in url

Suppose I have 3 (or more languages) on site. English, Italian, French. English being the default.

I want the homepage url to be:

My route is currently

Route::get('/{locale}', 'HomeController@index')->name('home');

This works for French, Italian but obviously not for English being just mysite.com/

I dont want another route like

Route::get('/', 'HomeController@index')

Because then I wouldn be able to simply call home in any language as

{{ route('home', $locale) }}

Whats the best solution?

Upvotes: 0

Views: 3729

Answers (2)

katsarov
katsarov

Reputation: 1822

One of my old solutions but still should work: In the beginning of routes.php

$locale = Request::segment(1);

if(in_array($locale, ['en','fr','it'])){
    app()->setLocale($locale);
}else{
    app()->setLocale('en');

    $locale = '';
}

Then

Route::group([
  'prefix' => $locale
], function(){ 
   Route::get('/demo', 'TestController@demo')->name('demo');
   ...
})

Important: You should always use named routes in this scenario. The generated URLs will then be for the current locale:

route('demo') will return /demo when app locale is english, and /it/demo when app locale is italian!

Upvotes: 4

TiTnOuK
TiTnOuK

Reputation: 173

Laravel allows optional parameters in route definition, so you can set local route parameter as optional for your usage :

Route::get('/{locale?}', 'HomeController@index')->name('home');

And in your HomeController, check the parameter to know if locale is present

public function index(Request $request, $locale = null) {
  if (empty($locale)) {
    $locale = 'en'; // english by default
  }

  ...
}

Hope it's helps you :)

Upvotes: 2

Related Questions