cretueusebiu / laravel-javascript by cretueusebiu

Add JavaScript variables to Laravel.
36,835
4
4
Package Data
Maintainer Username: cretueusebiu
Maintainer Contact: me@cretueusebiu.com (Cretu Eusebiu)
Package Create Date: 2016-07-24
Package Last Update: 2017-06-14
Home Page:
Language: PHP
License: MIT
Last Refreshed: 2024-11-14 15:02:49
Package Statistics
Total Downloads: 36,835
Monthly Downloads: 20
Daily Downloads: 1
Total Stars: 4
Total Watchers: 4
Total Forks: 3
Total Open Issues: 0

Add JavaScript variables from Laravel.

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

Installation

Install the package via Composer:

composer require cretueusebiu/laravel-javascript

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

// config/app.php

'providers' => [
    ...
    Eusebiu\JavaScript\JavaScriptServiceProvider::class,
],

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

Usage

In your controller:

<?php

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 = window.config.data.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:

<?php

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.