路由组以在Laravel 5.1中进行本地化

时间:2015-06-15 12:24:26

标签: laravel laravel-5 laravel-routing

我的网站上有三种语言:

en, fr, de

我希望网站上的所有网页都在第一段的网址中使用该语言,即

/page     ->set Locale as English
/de/page  ->set Locale as German
/fr/page  ->set Locale as French

知道如何将此应用于所有路线吗?必须根据第一个URL段设置语言,如果不是“de”或“fr”,则将语言设置为英语。谢谢!

1 个答案:

答案 0 :(得分:1)

我现在已经开始使用foreach循环了。

<?php

// routes.php

Route::group(['middleware' => 'lang'], function () {

    $langPrefixes = array_merge(config('app.langs'), ['']);

    foreach ($langPrefixes as $lang)
    {
        Route::get($lang . '/', [
            'uses' => 'PropertyController@index'
        ]);

        Route::get($lang . '/stuff', [
            'uses' => 'PropertyController@stuff'
        ]);
    }

});

在config / app.php中:

<?php

// config/app.php

'langs' => ['fr', 'de'], // new addition

中间件:

<?php

// Middleware/SetLanguage.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Foundation\Application;

class SetLanguage
{
    protected $app;

    /**
     * Get access to the IoC container
     *
     * @param  Illuminate\Foundation\Application  $auth
     * @return void
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (in_array($request->segment(1), $this->app['config']['app.langs']) )
        {
            // override 'en' as the app locale
            $this->app['config']['app.locale'] = $request->segment(1);
        }

        return $next($request);
    }
}