Laravel站点多语言部署

Posted by Nathan on 2018-11-15

部署多语言支持的Laravel 项目,主要有以下三件事情需要做:

  1. 增加可以用的 locales
  2. 在所有路由前加上语言前缀
  3. 增加一个中间件,用来检查当前是否用了一个合法的 locale

第一步, 添加可用的语言信息

打开 config/app.php ,增加如下格式的内容, ‘locale’ => ‘xx’

1
locales => ['en'=>'English', 'zh'=>'Chinese'],

第二部,给路由增加前缀

为了给路由增加前缀,我们修改 App/Providers/RouteServiceProvider.php 中的 map 方法,修改内容如下:

1
2
3
4
5
6
7
8
public function map(Router $router, Request $request)
{
$locale = $request->segment(1);
$this->app->setLocale($locale);
$router->group(['namespace' => $this->namespace, 'prefix' => $locale], function($router) {
require app_path('Http/routes.php');
});
}

当然,不要忘记在文件顶部引入命名空间:

1
2
use Illuminate\Routing\Router;
use Illuminate\Http\Request;

第三步 增加语言控制中间件

在app/Http/Middleware目录下,创建一个名为 Language.php 的中间件,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Routing\Redirector;
use Illuminate\Http\Request;
use Illuminate\Foundation\Application;
use Illuminate\Contracts\Routing\Middleware;

class Language implements Middleware {

public function __construct(Application $app, Redirector $redirector, Request $request) {
$this->app = $app;
$this->redirector = $redirector;
$this->request = $request;
}

/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Make sure current locale exists.
$locale = $request->segment(1);

if ( ! array_key_exists($locale, $this->app->config->get('app.locales'))) {
$segments = $request->segments();
$segments[0] = $this->app->config->get('app.fallback_locale');

return $this->redirector->to(implode('/', $segments));
}

$this->app->setLocale($locale);

return $next($request);
}

}

现在,把这个中间件在 app/Http/Kernel.php 中注册,并确保他是第一个。

1
2
3
4
5
6
7
8
9
10

protected $middleware = [
'App\Http\Middleware\Language',
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'Illuminate\Foundation\Http\Middleware\VerifyCsrfToken',
];

然后就ok了,试一下。