Search code examples
laravelvue.jstranslationinertiajs

Spatie Laravel Translation Loader with Inertia JS


Because I need to store translation text in the database so that users can update it, I'm using the spatie/laravel-translation-loader package. In my application, I'm combining Inertia JS and Vue 2. I'm looking for advice on how to effectively pass translation data to the Vue component.

Thanks.


Solution

  • I've used the following strategy:

    I've shared the following translation data:

    class HandleInertiaRequests extends Middleware
    ...
    public function share(Request $request)
    {
    ...
    
    'trans' => [
            'common' =>   LanguageLine::getTranslationsForGroup(app()->currentLocale(),'common')
        ],
    ...
    }
    ...
    

    Created trans() function and global mixin

    export default function(group, key) {
        let value = _.get(this.$page.props.trans[group], key);
        if (value) {
            return value;
        } else {
           return key;
        }
    }
    
    import trans from '@/utils/trans';
    Vue.prototype.$trans = trans;
    Vue.mixin({
        methods: {
            trans: trans
        },
    });
    

    used trans() in vue component as:

    <template>
    
    ...
     <h1> trans('common', 'dashboard') </h1>
    ...
    </template>