Laravel Translations Loader

Using Laravel translations in Javascript.

Have you ever wanted to use the same Laravel translations you use on the back-end in your front-end code?

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

It Instead of doing HTTP requests to fetch translation, the package enters in the middle of the asset complication process and translate your PHP translations files (JSON and PHP) into a JSON object so you can use however you like.

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

Show me the code

The first step, is to install the package using NPM or Yarn.

npm install @kirschbaum-development/laravel-translations-loader --save
yarn add @kirschbaum-development/laravel-translations-loader --save

Or, by using Yarn.

npm install @kirschbaum-development/laravel-translations-loader --save

Basically, in your javascript file, you just need to include the following line to import your language bundle.

import languageBundle from
'@kirschbaum-development/laravel-translations-loader!@kirschbaum-development/laravel-translations-loader';

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

{
    "en": {
        "auth": {
            "failed": "These credentials do not match our records."
        }
    },
    "es": {
        "auth": {
            "failed": "Estas credenciales no coinciden con nuestros registros."
        }
    }
}

Along with all other translations you may have on your translations folder.

There's options 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 check 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–18n

Notice you can directly pass the languageBundle object as a parameter into the VueI18n constructor.

import languageBundle from '@kirschbaum-development/laravel-translations-loader!@kirschbaum-development/laravel-translations-loader';
import VueI18n from 'vue-i18n';
Vue.use(VueI18n);
const i18n = new VueI18n({
    locale: window.Locale,
    messages: languageBundle,
})

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

<template>
    <span>{{ $t('auth.failed') }}</span>
    <!-- this will output the same as {{ trans('auth.failed') }} using Laravel -->
</template>
Tags: Open Source
Luis Dalmolin
Web Application Developer
Author Image

Interested in speaking with a developer?

Connect with us.
©2021 Kirschbaum Development Group LLC