Best way to send from php a variable to javascript, using laravel

12,928

Here is one solution to pass javascript variables. http://forumsarchive.laravel.io/viewtopic.php?id=2767

In Controller

// controller
$js_config = array(
    'BASE' => URL::base(),
    'FACEBOOK_APP' => Config::get('application.facebook_app')
);

return View::make('bla')
    ->with('js_config', $js_config);

In View

<script>
var config = <?php echo json_encode($js_config) ?>;

alert(config.BASE);
alert(config.FACEBOOK_APP.id);
alert(config.FACEBOOK_APP.channel_url);
</script>

Libraries are also available for that purpose

https://github.com/laracasts/PHP-Vars-To-Js-Transformer

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

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

There are multiple approaches for this problem

Share:
12,928
LuisKx
Author by

LuisKx

Updated on June 17, 2022

Comments

  • LuisKx
    LuisKx almost 2 years

    right now I'm sending a json from laravel to the View and populating a form, the problem is that I need to do certain modifications based in that data from javascript. Right now I use an Ajax request to ask for the exact data from the server, I think thats a little repetitive, and I know I can do something like (var data = {{$data}}) and use it in my js file.

    My question is, what is the best solution? Make an ajax call or make the variable directly from the view, I don't know if make the variable from the view is a bad practice or not.

    Thanks