Transform php variables to javascript

How to transform your PHP to JavaScript – Laravel

Spread the love

Often, you find yourself in a situation where you want to pass your server-side variables, string, collection to JavaScript. By traditional old ways it can be a bit of pain especially when your application grows.

In this tutorial I will guide on how to pass php variable to JavaScript, elegantly. For this purpose, Jeffery Way from Laracasts has created a package called utilities with following name space: laracasts/utilities.

Package Installation

Run following command in composer:

composer require laracasts/utilities

Put the following entry in your app.php file in providers array:

// config/app.php

'providers' => [
    '...',
    'Laracasts\Utilities\JavaScript\JavaScriptServiceProvider'
];

Run following command to publish vendor:

php artisan vendor:publish

// Or...

php artisan vendor:publish --provider="Laracasts\Utilities\JavaScript\JavaScriptServiceProvider"

Package Config

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | View to Bind JavaScript Vars To
    |--------------------------------------------------------------------------
    |
    | Set this value to the name of the view (or partial) that
    | you want to prepend all JavaScript variables to.
    |
    */
    'bind_js_vars_to_this_view' => 'footer',

    /*
    |--------------------------------------------------------------------------
    | JavaScript Namespace
    |--------------------------------------------------------------------------
    |
    | By default, we'll add variables to the global window object. However,
    | it's recommended that you change this to some namespace - anything.
    | That way, you can access vars, like "SomeNamespace.someVariable."
    |
    */
    'js_namespace' => 'window'

];

If you open config file of this package, you will find two configuration keys:

  • bind_js_vars_to_this_view (which view to append those transformed variables, the most appropriate view to bind here can be footer)
  • js_namespace (here as you can see window, so all the transformed variables will be added to global window object)

Package Usage

public function index()
{
    JavaScript::put([
        'foo' => 'bar',
        'user' => User::first(),
        'age' => 29
    ]);

    return View::make('hello');
}

In Laravel 5, of course add use JavaScript; to the top of your controller.

As you can see in above code, I have passed three types of variables one is string, second one is object, and third one is integer. So, at js side I want these variables to be according to their types.

console.log(foo); // bar
console.log(user); // User Obj
console.log(age); // 29

As you can see below in my console results that I have those variables available in my php_to_js.js file, and all the variable types are according.

2 thoughts to “How to transform your PHP to JavaScript – Laravel”

Comments are closed.