Add JavaScript variables to Laravel.

0.2.1 2017-03-09 13:55 UTC

This package is auto-updated.

Last update: 2024-07-14 04:57:45 UTC


Latest Stable Version Build Status Total Downloads

Add JavaScript variables from Laravel.

ScriptVariables::add('user', Auth::user());
const user = window.config.user


Install the package via Composer:

composer require cretueusebiu/laravel-javascript

Next, you need to register the service provider and facade:

// config/app.php

'providers' => [

'aliases' => [
    'ScriptVariables' => Eusebiu\JavaScript\Facades\ScriptVariables::class,


In your controller:


namespace App\Http\Controllers;

use Eusebiu\JavaScript\Facades\ScriptVariables;

class HomeController extends Controller
    public function home()
        ScriptVariables::add('key', 'value');
        ScriptVariables::add('data.user', User::first());

Next, in your blade view add:

{{ ScriptVariables::render() }}

Then in your JavaScript you can use:

const key = window.config.key
const user =

To customize the namespace use ScriptVariables::render('custom').

Global Variables

You can register global variables (like the current user or csrf token) in your AppServiceProvider:


namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Eusebiu\JavaScript\Facades\ScriptVariables;

class AppServiceProvider extends ServiceProvider
    public function boot()
        ScriptVariables::add(function () {
            return [
                'csrfToken' => csrf_token(),
                'currentUser' => auth()->user(),

Note that the variables must be passed via a closure.