Question

Hy i have this http://laravel.io/bin/jaPB

The problem is when i go to: domain.com -> it serves the homepage (wich is ok) domain.com/foo -> it serves a subpage (still ok)

but when i go from one of those to: domain.com/en -> it gives an error (not ok)

But after hitting refresh its ok.

So again when i'm on domain.com/en first time error after refresh ok Same goes to subpage like domain.com/en/contact first time error after refresh ok

I would point out that the error says first time it tries to go to PublicPageController@subpage but this shouldn't happen when i go to domain.com/en it should need to go to PublicPageController@homepage

Any idea ? Thank you all.

Was it helpful?

Solution

My guess here form looking at the way you set up the locale-based routes is that the Session::get('urilang) isn't set the first time you visit, hence the error, and is only set once you've been to a page first.

Now, I haven't yet had to deal with multilingual sites, but as far as I'm aware the way you're doing it is not the correct way. Instead think of the lang key as a URI parameter, and use the filter to validate and set it for the routes. Something a bit like the below code:

// Main and subpage - not default language
Route::group(array('prefix' => '{lang}', 'before' => 'detectLanguage'), function () {
    Route::get('', 'PublicPage@homepage');
    Route::get('{slug}', 'PublicPage@subpage');
});

// Main and subpage - default language
Route::group(array('before' => 'setDefaultLanguage'), function () {
    Route::get('/', 'PublicPage@homepage');
    Route::get('/{slug}', 'PublicPage@subpage');
});

Route::filter('detectLanguage', function($route, $request, $response, $value){
    // hopefully we could do something here with our named route parameter "lang" - not really on sure the details though

    // set default 
    $locale = 'hu'; 
    $lang = '';

    // The 'en' -> would come from db and if there is more i would of corse use in array
    if (Request::segment(1) == 'en') 
    {
        $lang = 'en';
        $locale = 'en';
    }

    App::setLocale($locale);
    Session::put('uriLang', $lang);
    Session::put('locale', $locale); 
});


Route::filter('setDefaultLanguage', function($route, $request, $response, $value){
    App::setLocale('hu');
    Session::put('uriLang', '');
    Session::put('locale', 'hu'); 
});

I don't know if you can use a segment variable in a Route::group prefix, but you should certainly have a go at it as it'd be the most useful.

That said, I wouldn't advise setting up default language routes that mimic specific language routes but without the language segment. If I were you, I'd set up a special root route that will redirect to /{defaultlang}/ just so you have fewer routing issues.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top