Reputation: 31
I'm making a js localizator using service provider, and I need to get current locale to fetch current lang translations and pass to js. Everything works, but App::getLocale() keeps returning default app language.
I tried to do this using both middlware and view composer based on others issue threads in laracasts and stackoverflow, but nothing helps. Here's links
https://laracasts.com/discuss/channels/laravel/get-current-locale-in-app-service-provider
Getting locale language at provider class in Laravel
Laravel get getCurrentLocale() in AppServiceProvider
class JstranslateServiceProvider extends ServiceProvider
{
protected $langPath;
public function __construct()
{
$locale = App::getLocale();
$this->langPath = resource_path('lang/'.$locale);
dd($locale);
}
}
dd($locale);
output is always 'en'
, despite the current language.
I made js localization using this guide Link, it seems to be working for them
Upvotes: 1
Views: 4415
Reputation: 234
I'm using Lumen version 5.8 and figured out how to get the current locale:
app('translator')->getLocale();
Upvotes: 0
Reputation: 31
Getting locale in boot and putting everything in composer solved my issue.
public function boot()
{
Cache::forget('translations');
view()->composer("layouts.app", function () {
$locale = App::getLocale();
if($locale == 'us')
$locale = 'en';
$this->langPath = resource_path('lang/'.$locale);
Cache::rememberForever('translations', function () {
return collect(File::allFiles($this->langPath))->flatMap( function ($file) {
return [
($translation = $file->getBasename('.php')) => trans($translation),
];
})->toJson(JSON_UNESCAPED_UNICODE);
});
});
}
Upvotes: 0
Reputation: 3040
Do this outside of a constructor in the Service Provider.
These classes are instantiated before Laravel does anything so it is likely whatever you have written in your middleware/view composer hasn't taken affect.
Instead you should be doing this either in the boot
or register
method.
Upvotes: 1