Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dneykov's avatar

Translations is javascript files

Hi everyone, this is my first post here. I'm using Laravel for on of my projects and I need an advise about translations. In blade templates I'm using @lang and everything works perfect. The problem is that I have some strings in js files and I don't know how to translate them. I saw there are some packages but don't know if they are reliable. I'll appreciate any help. Thanks

0 likes
8 replies
zachleigh's avatar

Are you using a js framework or anything? I usually just send the translation data to the javascript in the blade template. This is easy if you're using something like Vue.

1 like
dneykov's avatar

No, just simple javascript files I use only jQuery .

d3xt3r's avatar

The problem is that I have some strings in js files and I don't know how to translate them.

What do you mean, where are you translating them ?

dneykov's avatar

They are in messages.php but don' t know hot to use in js file. In blade I'm using

@lang('messages.hello')

How to call this translation in js file?

d3xt3r's avatar

You can't, not directly. If you want to access it at runtime from within js

  1. Either have an ajax-route setup for your translations.

  2. Place them at some place on your html file, so that you can retrieve it from within js.

// In blade file
    <meta name="en.messages.hello" content="@lang('messages.hello',[], 'en')">
    <meta name="fr.messages.hello" content="@lang('messages.hello',[], 'fr')">

// Now you can easily access them from js.

martinbean's avatar

@dneykov Where do you need translated strings? I tend to pass any strings in mark-up to JavaScript, like this:

<button type="submit" data-confirm="{{ trans('messages.confirm_delete') }}">
$('[data-confirm]').on('click', function (e) {
    var message = $(this).data('confirm'); // Will use translated string from Blade
    
    if (! confirm(message)) {
        e.preventDefault();
        e.stopImmediatePropagation();
    }
});
4 likes
HashmatWaziri's avatar

I used the https://github.com/rmariuzzo/Laravel-JS-Localization and worked without any issues.

Reminder: add asset('messages.js') inside your script tag to load before you use

and then do your implementation for example in my case :

            $('.join-now').html("<a class='dropdown-toggle' href='#' data-
           toggle='dropdown'>" +Lang.get('home.Navigation.logout')+"</a>");

Please or to participate in this conversation.