第一步: 新建所有的语言包文件 resources/lang

messages.php

就是返回一个数组 return [] 格式

中文的:

return [
 "test" => "这里是测试",
 "test1" => "继续测试",
 ......
];

英文的:

return [
 "test" => "this is a test...",
 "test1" => "test again...",
 ......
];

各种语言中的元素键名是对应

第二步:配置文件 app/config/app.php

'locale' => 'zh',
'locales' => ['zh','en','cht'], //包含的语言种类
'fallback_locale' => 'cht',

第三步:处理多语言切换的控制器以及方法

<?php
namespace App\Http\Controllers\Home;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Session;
class LangController extends Controller{
 /**
  * 切换语言包
  * @param Request $request
  */
 public function language(Request $request){
  if($request->ajax()) { //Ajax请求访问
   $lang = $request->all();
   $lang = $lang['lang'];
   App::setLocale($lang); //配置默认语言
   $request->session()->put('language',$lang); //存到session
   return App::getLocale();
  }else{
   if($request->session()->has('language')){
    $res = $request->session()->get('language'); //获取session
    return $res;
   }
  
  }
 }
}

第四步:blade模板

<meta name="csrf-token" content="{{ csrf_token() }}">
<select name="lang" id="lang">
 <option value="zh" @if(Session::get('language') == 'zh') selected @endif>中文</option>
 <option value="cht" @if(Session::get('language') == 'cht') selected @endif>繁体</option>
 <option value="en" @if(Session::get('language') == 'en') selected @endif>English</option>
</select>

js部分

<script>
 $("#lang").change(function(){
  $.ajaxSetup({headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}});
  $.post(
    "{{url('lang')}}",
    {
     lang:$("#lang").val()
    },
    function(d){
     if(d){
      console.log(d);
      location.reload(); //重新刷新页面
     }
    }
  );
 });
</script>

第五步: 中间件的设置-middleware(每一次请求,每个中间件都会执行) app/http/middleware下添加Language.php 内容如下

<?php
namespace App\Http\Middleware;
  
use Closure;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Session;
  
class Language
{
 /**
  * @param $request
  * @param Closure $next
  * @return mixed
  */
 public function handle($request, Closure $next)
 {
  if (Session::has('language') AND in_array(Session::get('language'), Config::get('app.locales'))) {
   App::setLocale(Session::get('language'));
  }
  else { // This is optional as Laravel will automatically set the fallback language if there is none specified
   App::setLocale(Config::get('app.locale'));
  }
  return $next($request);
 }
  
}

配置app/http/middleware/kernel.php 添加Language