in Basset, Our Authors

How to pass data to JavaScript with Basset?

This article explains how to pass data from server PHP to JavaScript with Basset – better asset management for Laravel.

Sometimes you will want to pass data from server PHP to JavaScript but without API. It can be to preload data, or to pass some server specific data which shouldn’t be in API’s.

You can use Basset\Javascript class for that. Whatever you set on this class will be available from the browser JavaScript runtime.


To use Basset\Javascript go into your controller where you want to pass data to JavaScript. Add use Basset\Javascript and use Laravel Method Injection to inject the instance of it.

<?php namespace App\Http\Controllers;

use Auth;
use Basset\Javascript;
use Illuminate\Routing\Controller;

class AdminController extends Controller {

    function index(Javascript $js)
        $js->user = Auth::user();
        $js->basePath = route("admin");

        return view('admin.index');


And inside your view in head tag you will need to write:

<!DOCTYPE html>
    <meta charset="utf-8">
    <title> Admin </title>
    <?php echo $js ?>

This will add a script tag which will export data that you set to $js variable in controller. By default it exports data to window.preload variable. So in your JavaScript you can use:


But If you want to use some other window variable name, for example config,  you can type:

<?php echo $js("config") ?>

This will export data to window.config variable. Awesome!