Php vars @ JS with the help of a Laravel SP & View Composer

George Drakakis
2 min readMay 9, 2017

--

Few days ago I was experimenting with the common problem of passing php locale variables to Javascript and I wondered if I could do that avoiding extra package dependencies. I kinda like the laravel way of key / value pairs for locale strings and I would love to keep that logic in my JS side somehow. So I came up with a solution that I think it’s really flexible and easy for many cases.

At first, although I could just use the Application service provider, I created a brand new Service Provider and called it `JavascriptVarsProvider` just for clarity.

As always, in order for a Service provider to work, you need to let Laravel know about it in config/app.php

config/app.php

In the boot method of the Service provider I added a view composer and I just assigned a variable called ‘jsVars’. The value of this variable is the interesting part. It’s a json_encoded include of a complete file that lives in the languages directory.

So next step is to create that file, each for every language in your app.

resources/lang/el/jsvars.php

Ok, now that everything is in place, only thing left is to actually get the ‘jsVariable’ in JS side. Adding the following script line in the blade template before any of your JS code will do the trick.

template.base blade file

Done.

Now each time I want a new php lang variable I just add a new key in lang/jsvars.php and access it accordingly to my javascript by using a syntax like this ‘jsVars.ErrorMsgTxt’. Since the language is determined server side in runtime, you got the right language in that ‘ErrorMsgTxt’ key, every time! Of course you are not limited to have locale strings to the ‘jsVar’ variable, you can have config values as well.

In my case I wanted to have different responses according the language, so this came really handy.

--

--