Search code examples
laravellocalizationlaravel-localization

Laravel get getCurrentLocale() in AppServiceProvider


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());

}

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.

What may I be doing wrong?

Thanks in advance for any help


Solution

  • 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'
            );
        }
    }
    

    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 and altLocale will be available on all views of your application