How to use Laravel translations in Javascript?

Have you ever wished to use translations in your front-end code (like Vue.js) same Laravel translations you use on the back-end?

Laravel Translations Loader is a webpack loader that allows you to load Laravel translations into your javascript bundle.

This package reads and normalizes translations files (including PHP keyed translations files) during the asset compilation process. It normalizes to a javascript object format so you can use how you like.

It works out of the box with packages like vue-i18n or with a few configurations with the popular i18next.

Installation

In your app.js file, just add the following import.

This will load and parse all your language files, including PHP and JSON translations. The languageBundle will look something like this:

And so on, with all your languages and all your translation strings.

There are choices for loading either just PHP or JSON translations files, as well to add a namespace between the lang keys and the actual translations that some packages require. You can examine the different loading options on the readme of the project. And please fill an issue if you have any troubles or suggestions.

Example using vue-i18n
Notice you can directly pass the languageBundle object as a parameter into the VueI18n constructor.

And on any vue component, you can just use the $t function, like the following example:

Leave a Reply

Your email address will not be published. Required fields are marked *