迈出脚步
体验世界

Laravel切换多语言操作

第一步:新建所有的语言包文件  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

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Laravel\Jetstream\Http\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\Language::class,//将新建的middleware加入到这里
        ],

最后别忘了路由部分

Route::post('lang',[LangController::class,'language']);

关于blade模板里面调用:

先新建一个自定义函数:

app/Helpers/functions.php(若没有此目录或文件,新建一个即可)

<?php

function lang($code,$lang='zh'){
    $lang= empty($lang)?'zh':$lang;
    $code= preg_replace('/[^0-9a-zA-z.-_ ]/', '', $code);
    $trans=trans($code,[],'',$lang);
    if(empty($trans)||$trans==$code){
        $trans= ucwords(preg_replace('/([0-9a-zA-z-_ ]*[.])*/', '', $code));
    }
    return $trans;
}

然后在根目录composer.json文件中配置一下

autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        },
        "files":[
            "app/Helpers/functions.php"
        ]//添加此项即可

然后运行命令:

 composer dump-autoload

blade模板文件中,使用 {{lang(‘lang.test’)}}调用即可

赞(0) 喜欢我
未经允许不得转载:王威 » Laravel切换多语言操作
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏