Language:

Search

Implementing Laravel Localization in JavaScript

  • Share this:
Implementing Laravel Localization in JavaScript

Recently, I came across a scenario where i need to use localization into my JS files & what we actually want to achieve is to pass my translation files from lang directory to my JS files with some sort of a function or variable. Let's see a simple approach to accomplish this.

Also Read: Secure Laravel Deployment to Production

Step # 01 - Create a ServiceProvider

Let's start by creating a ServiceProvider and name it LocalizationServiceProvider likeso,

php artisan make:provider LocalizationServiceProvider

Now in our root method of LocalizationServiceProvider.php

$this->langPath = resource_path( 'lang/'. App::getLocale() );
Cache::rememberForever( 'translations', function () {
return collect( File::allFiles( $this->langPath ) )->flatMap( function ( $file ) {
return [
$translation = $file->getBasename( '.php' ) => trans( $translation ),
];
} )->toJson();
} );

Also Read: Top 10 reasons to choose Laravel

It will save translations attribute to Cache forever until you clear your application's cache (php artisan cache:clear) or pull translations our of your cache.(Cache:pull('translations'))

Don't forget to register your LocalizationServiceProvider in your config/app.php

Also Read: Remove index.php from URL in Laravel

Step # 02 - Pass on to JS

Now in our footer.blade.php, we can pass the translations variable likeso

<script>
var translations = {!! \Cache::get('translations') !!};
</script>

Step # 03 - Create a function in JS

We'll now create a simple function inside of any of our JavaScript file to get data from translations and play around with it. What we need here is to use the basic features of Laravel's translator and we want to retrieve a string paired with the given key.

Also Read: Polymorphic Relations in Laravel

function trans(key, replace = {}) {
var translation = key.split('.').reduce((t, i) => t[i] || null, window.translations);

for (var placeholder in replace) {
translation = translation.replace(`:${placeholder}`, replace[placeholder]);
}
return translation;
}

Step # 04 - Use Case

We can now simply use our translations in our JS files likeso

trans('auth.validation.success'),

Fixing a Glitch

In my case, we have a couple of languages i.e. en, vi, es etc. But on switches languages, we still fetching records from default (en) language only. Let's fix this.

So, on getting App::getLocale();, its en by default and yet save the en language files into the Cache and until we clear out our cache, it will remain there no matter what.

Also Read: Localization in Laravel

For a simple fix, I've done the following. Let know in the comment section section if you've a better solution for this.

Again in the root method of our LocalizationServiceProvider

if ( request()->is( 'en', 'en/*' ) ) {
Cache::pull( 'translations' );
App::setLocale( 'en' );
$this->langPath = resource_path( 'lang/en' );
} elseif ( request()->is( 'vi', 'vi/*' ) ) {
Cache::pull( 'translations' );
App::setLocale( 'vi' );
$this->langPath = resource_path( 'lang/vi' );
}

Conclusion

We've successfully used Laravel's localization in our JS files. If you've any feedback or comments, do write us in the comment section below.

This idea of this article was inspired from Using Laravel's Localization in JS

Usama Muneer

Usama Muneer

A web enthusiastic, self-motivated & detail-oriented professional Full-Stack Web Developer from Karachi, Pakistan with experience in developing applications using JavaScript, WordPress & Laravel specifically. Loves to write on different web technologies with an equally useful skill to make some sense out of it.