Sometimes you may need to generate some information server side and make it available as a javascript object in your Laravel application. Luckily Jeffrey Way, Author of Laracasts, has created an easy to use package for it.

After you have installed the package via composer, and followed the installation instructions on GitHub, you are ready to rock and roll.

First, you need to publish the config file to tell the plugin what view to bind the javascript to.

The only limitation I see with the package as it is currently is that it only allows you to bind to one view, so if you have a large application with frontend and backend views, as laid out in my boilerplate package, you will need a master layout for your master layouts.

Regardless, not that big of a deal to get around.

Next, you need to use the Javascript facade in your controller to tell the method to inject the javascript into the view:

Now in that view, if you do a console.log(test), you will get it works!.

A step further:

I like to make global helper functions for facades I use often, in a helpers.php file that is located in the /app folder root. It is autoloaded in composer.json as:

Then, in helpers.php I do this:

Now, in your controller, you can lose the use statement and change the call to this:

You can do this with any facade you use really often. I just wouldn’t abuse it as it does add load to your application.