多语言切换
config/app.php 中 locale 中默认为‘en’
'locale' => 'zh_CN',
建立LanguageController
namespace App\Http\Controllers; class LanguageController extends Controller { public function setlocale() { $lang = session('language'); if ($lang == 'zh_CN') { session(['language' => 'en']); } else { session(['language' => 'zh_CN']); } return view('lang'); } }
添加路由
Route::get('lang', 'LanguageController@setlocale')->name('lang');
建立Language中间件
namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\App; class Language { public function handle($request, Closure $next) { if (session()->has('language')) { App::setLocale(session('language')); } else { session(['language' => App::getLocale()]); } return $next($request); } }
将Language中间件添加到中间件组中
namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { protected $middleware = [ .... ]; protected $middlewareGroups = [ 'web' => [ ... \App\Http\Middleware\Language::class ], 'api' => [ ... ], ]; protected $routeMiddleware = [ .... ]; }
这样访问任何路由都会执行Language中间件中handle()的内容
resources/lang目录下比照en文件夹建立对应的语言包,blade页面访问使用 {{__('en文件夹下文件名.key名称')}}
标签:laravel,lang,Http,语言,language,App,session,构建,Language From: https://www.cnblogs.com/caroline2016/p/16905647.html