Felix
Felix

Reputation: 812

URL based locale detection in Laravel 4

In Laravel 3 I used to get the locale detected, based on the first segment of the request URL.

application/config/application.php:

/*
|--------------------------------------------------------------------------
| Supported Languages
|--------------------------------------------------------------------------
|
| These languages may also be supported by your application. If a request
| enters your application with a URI beginning with one of these values
| the default language will automatically be set to that language.
|
*/

'languages' => array(
    'en',
    'de',
    'fr',
),

So I can define a Route

Route::get('foo', function() {
    echo 'Foo';
});

and have it accessed via:

GET /en/foo
GET /de/foo
GET /fr/foo

Laravel 4 removes this feature.

Can I get this behaviour back?

I tried to manually implement it, but since I want it on every Request, I don't want to specify the language variable in every route (The Route above should work with my implementation). Here is my solution:

App::before(function($request)
{
    $language = Request::segment(1);

    if(in_array($language, Config::get('cms.available_languages')))
    {
        App::setLocale($language);
    }

    // Since locale is already set, 
    // I want to remove the language from the request URL (/en/foo => /foo)
    // So I can route via Route::get('foo', ...)
    $request->removeSegment(1);
}

But there is no way I know of to remove the language from the request URL, so I get 404, because en/foo is not specified.

What can I change to get this to work?

Upvotes: 1

Views: 4323

Answers (1)

Mike Rockétt
Mike Rockétt

Reputation: 9007

See this forum post: http://forums.laravel.io/viewtopic.php?id=7458

Here, we are simply detecting the language by picking up the URI prefix, and then applying it to a group of Routes.

Then, to compile those URLs for your Views, you would simply used Named Routes.

To me, it is the best way of going about it for now.

Upvotes: 2

Related Questions