Khan Muhammad
Khan Muhammad

Reputation: 420

Laravel - routing and language code

I need to put a language code in my url but not when it is the default one.

Here is the code in routes.php file in Laravel 4.2

I need root structure like:

default language => http://website.com/RegistrationStep1
other language => http://website.com/language/RegistrationStep1

Route::group(['prefix' => '{lang?}', 'before' => 'localization'], function()
{

    Route::get('/', function() {
        return View::make('hello');
    });

    Route::get('registration/step1', 'RegistrationController@getRegistrationStep1');

    Route::post('registration/step1', 'RegistrationController@postRegistrationStep1');
});

I am getting error when I call url without the language param in url

Upvotes: 1

Views: 3659

Answers (1)

Hieu Le
Hieu Le

Reputation: 8415

First, define your available languages:

# in app/config/app.php
'available_locales' => array('de', 'en', 'es', 'fr', 'it'),

In your routes.php check if the first segment of current URI is a valid language shortcut before register your prefix in route group.

$locale = Request::segment(1);

if (in_array($locale, Config::get('app.available_locales'))) {
    \App::setLocale($locale);
} else {
    $locale = null;
}

Route::group(array('prefix' => $locale), function()
{

    //your routes here

});

See the link http://learninglaravel.net/language-switching-in-laravel-4/link

You can also use this package for your task: mcamara/laravel-localization

Upvotes: 6

Related Questions