Laravel在AppServiceProvider中获取getCurrentLocale() [英] Laravel get getCurrentLocale() in AppServiceProvider

查看:211
本文介绍了Laravel在AppServiceProvider中获取getCurrentLocale()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Laravel AppServiceProvider类的boot()方法中获取LaravelLocalization::getCurrentLocale(),尽管我的默认语言环境是 pt ,但我总是得到 en .我正在使用的软件包是mcamara/laravel-localization.我拥有的代码:

I'm trying to get the LaravelLocalization::getCurrentLocale() in the boot() method of the Laravel AppServiceProvider class, and although my default locale is pt I always get the en. The package I'm using is mcamara/laravel-localization. Code I have:

public function boot()
{
    Schema::defaultStringLength(191);

    // Twitter view share
    $twitter = Twitter::getUserTimeline(['screen_name' => env('TWITTER_USER'), 'count' => 3, 'format' => 'object']);
    view()->share('twitter', $twitter);

    // Current language code view share
    $language = LaravelLocalization::getCurrentLocale();
    view()->share('lang', $language);

    // Practice Areas
    view()->share('practice_areas', \App\Models\PracticeArea::with('children')->orderBy('area_name')->where(['parent_id' => 0, 'language' => $language])->get());

}

我可能将其放置在错误的位置,因为当我尝试共享practice_areas变量时,即使切换了语言,它总是将其设置为 en .

I'm probably placing this in the wrong place because when I try to share the practice_areas variable it always sets it as en even if the language is switched.

我可能做错了什么?

在此先感谢您的帮助

推荐答案

通过使用专用的服务提供程序和视图编写器类解决了完全相同的问题,如下所示:

Faced the exact same problem, solved by using a dedicated Service Provider and a view composer class, like so:

<?php

namespace App\Providers;

use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class LocalizationServiceProvider extends ServiceProvider
{
    public function boot() {
        View::composer(
            '*', 'App\Http\ViewComposers\LocalizationComposer'
        );
    }
}

,然后在LocalizationComposer类上:

and then on LocalizationComposer class:

<?php

namespace App\Http\ViewComposers;

use Illuminate\View\View;
use LaravelLocalization;

class LocalizationComposer {

    public function compose(View $view)
    {
        $view->with('currentLocale', LaravelLocalization::getCurrentLocale());
        $view->with('altLocale', config('app.fallback_locale'));
    }

}

currentLocale和altLocale将在您的应用程序的所有视图上可用

currentLocale and altLocale will be available on all views of your application

这篇关于Laravel在AppServiceProvider中获取getCurrentLocale()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆