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?
2
Answers
If you want to use
PHP
variable in thescript
tag inside theblade
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 )
or use
@JSON
blade directive for objects and arrays :Then use
myVar
in your JS scriptsfor your example :
I hope it helps
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):
fetch()
echo
them into your JS using blade as @Royal_MGH suggested