先增加一个中间件app/Http/Middleware/LangMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
class LangMiddleware
{
/**
* 多语言处理中间件
* @param $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$host = $request->getHost();
switch ($host){
case 'zh.baidu.io':
$lang = 'zh';
break;
case 'en.baidu.io':
$lang = 'en';
break;
default:
$lang = 'zh';
}
app('translator')->setLocale($lang);
return $next($request);
}
}
然后在bootstrap/app.php里注册为全局中间件
<?php
$app->middleware([
# App\Http\Middleware\CrossHttp::class,
App\Http\Middleware\LangMiddleware::class,
# App\Http\Middleware\ExampleMiddleware::class
]);
语言定义文件在 resource/lang目录下:
resources/lang/zh/message.php内容实例:
<?php
return [
'validation_failed' => '验证失败。',
];
代码里调用翻译:
use Illuminate\Support\Facades\Lang;
$output = Lang::get('message.validation_failed');