Home > Mobile >  Using Laravel language variables in js
Using Laravel language variables in js

Time:09-26

I am using multiple languages in Laravel. I am getting the results of some data via Javascript files. My problem is that I need to convert the results from javascript to language. For this reason, I need to define language variables in javascript.

My language variables are like this;

{{ __('folder/folder.file') }}

sample javascript content

if (response == 0) {
    e.innerHTML = `You have received no orders in the last 90 days.`;
} else {
    e.innerHTML = `{{ __('folder/folder.file') }}`;
}

As you can see I didn't define the {{ __('folder/folder.file') }} language variables but it didn't work. How can I use it correctly here?

CodePudding user response:

If you want to use PHP variable in the script tag inside the blade template your code is working well. But for external JS:

Use PHP and Laravel methods in Javascript

Define your language variable:( above your js code )

<script>    
    var myVar = {!! __('folder/folder.file') !!};
</script>

or use @JSON blade directive for objects and arrays :

var myVar = @json($array);

Then use myVar in your JS scripts

for your example :

if (response == 0) {
    e.innerHTML = `You have received no orders in the last 90 days.`;
} else {
    e.innerHTML = myVar;
}

I hope it helps

CodePudding user response:

You can't directly access PHP variables or functions in JavaScript, since when the Browser delivers contents of the requested URL to the client, it doesn't deliver PHP code but HTML (from your routes/web.php) or JSON (from your routes/api.php) depending on the case.

So, you need a way to access your translation variables some way or another (one of these options):

  1. Make resources/lang publically accessable and use JSON files, that can be requested via fetch()
  2. Make an endpoint in your routes/api.php to deliver your translations
  3. echo them into your JS using blade as @Royal_MGH suggested
  • Related