Transform PHP data to JavaScript.

Overview

Transform PHP Vars to JavaScript

Build Status

Often, you'll find yourself in situations, where you want to pass some server-side string/array/collection/whatever to your JavaScript. Traditionally, this can be a bit of a pain - especially as your app grows.

This package simplifies the process drastically.

Installation

Begin by installing this package through Composer.

composer require laracasts/utilities

If you use Laravel 4: instead install ~1.0 of this package (and use the documentation for that release). For Laravel 5 (or non-Laravel), ~2.0 will do the trick!

Laravel Users

For Laravel users, there is a service provider you can make use of to automatically register the necessary bindings.

Laravel 5.5+ users: this step may be skipped, as we can auto-register the package with the framework.

// config/app.php

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

When this provider is booted, you'll gain access to a helpful JavaScript facade, which you may use in your controllers.

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.

Using the code above, you'll now be able to access foo, user, and age from your JavaScript.

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

This package, by default, binds your JavaScript variables to a "footer" view, which you will include. For example:

<body>
    <h1>My Page</h1>

    @include ('footer') // <-- Variables prepended to this view
</body>

Naturally, you can change this default to a different view. See below.

Defaults

If using Laravel, there are only two configuration options that you'll need to worry about. First, publish the default configuration.

php artisan vendor:publish

// Or...

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

This will add a new configuration file to: config/javascript.php.

<?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'

];

bind_js_vars_to_this_view

You need to update this file to specify which view you want your new JavaScript variables to be prepended to. Typically, your footer is a good place for this.

If you include something like a layouts/partials/footer partial, where you store your footer and script references, then make the bind_js_vars_to_this_view key equal to that path. Behind the scenes, the Laravel implementation of this package will listen for when that view is composed, and essentially paste the JS variables within it.

js_namespace

By default, all JavaScript vars will be nested under the global window object. You'll likely want to change this. Update the js_namespace key with the name of your desired JavaScript namespace. It can be anything. Just remember: if you change this setting (which you should), then you'll access all JavaScript variables, like so:

MyNewNamespace.varName

Note

Run this artisan command after changing the view path.

php artisan config:clear

Symfony2

To use this component in Symfony2 applications you can try this bundle, built on top of PHP-Vars-To-Js-Transformer.

Without Laravel

If you're not using Laravel, then you'll need to hard-wire things yourself. (Or, feel free to submit a pull request with an implementation for your desired framework.)

First, create an implementation of the Laracasts\Utilities\JavaScript\ViewBinder interface. This class is in charge of inserting the given JavaScript into your view/page.

<?php

class MyAppViewBinder implements Laracasts\Utilities\JavaScript\ViewBinder {

    // $js will contain your JS-formatted variable initializations
    public function bind($js)
    {
        // Do what you need to do to add this JavaScript to
        // the appropriate place in your app.
    }
}

Next, put it all together:

use Laracasts\Utilities\JavaScript\Transformers\Transformer;

$binder = new MyAppViewBinder;

$javascript = new Transformer($binder, 'window'); // change window to your desired namespace

$javascript->put(['foo' => 'bar']);

Now, you can access window.foo from your JavaScript.

Remember, though, this is only necessary if you aren't using Laravel. If you are, then just reference the service provider, as demonstrated above.

License

View the license for this repo.

Comments
  • Its not working for Laravel 5.2 ?

    Its not working for Laravel 5.2 ?

    Previously I was used this package in laravel 5.1 & I recently Migrated to 5.2 there I am facing problem this package not working in 5.2 & I dont know suport is there for 5.2 or not

    opened by srikanth240369 19
  • Vars are not getting bind to View

    Vars are not getting bind to View

    Hey Jeffrey,

    for me the setting for a custom View to bind the var dose not work.

    'bind_js_vars_to_this_view' => 'layouts.elements.footer'

    but the vars i try to bind via JavaScript::put([ 'mydata' => 'foobar']); is not set. elements.footer gets included in layouts.master which extends all my Blade Files.

    opened by pascalschwientek 11
  • Javascript class not found

    Javascript class not found

    I get error Javascript class not found until I add use Laracasts\Utilities\JavaScript\Facades\JavaScript. I'm not using any class named javascript or added alias for that name

    opened by filipzelic 10
  • Not working for Laravel 5.3

    Not working for Laravel 5.3

    I've followed the documentation very closely and it's still missing something, perhaps namespace related?

    Here's my composer.json:

        "require": {
            "php": ">=5.6.4",
            "laravel/framework": "5.3.*",
    	"laracasts/utilities": "~2.0"
        },
    

    Then in cmd:

    composer update

    results in vendor\laracasts\utilities\ as expected

    Then I modify app.php:

        'providers' => [
            /*
             * Laravel Framework Service Providers...
             */
            ...
            `Laracasts\Utilities\JavaScript\JavaScriptServiceProvider`
        ],
    

    Here's the part where I think there's definitely some issue in 5.3, because php artisan vendor:publish gives the following output:

    Copied Directory [\vendor\laravel\framework\src\Illuminate\Notifications\resources\views] To [\resources\views\vendor\notifications]
    Copied Directory [\vendor\laravel\framework\src\Illuminate\Pagination\resources\views] To [\resources\views\vendor\pagination]
    Publishing complete for tag []!
    

    No mention of the config for javascript, and there's no javascript.php file copied to config/

    But maybe it will still work, so in my IndexController.php

    namespace App\Http\Controllers;
    ...
    use JavaScript;
    ...
    class IndexController extends Controller
    {
      public function getIndex(){
      JavaScript::put([
        'foo' => 'bar'
        ]);
    

    Results in the following error:

    FatalThrowableError in IndexController.php line 38:
    Class 'JavaScript' not found
    
    opened by mschink 6
  • Sending 0 value

    Sending 0 value

    Hey,

    i've found a problem when sending 0 value to a variable.

    Nothing is displayed so an error is trigger.

    you need to add + to make javascript understanding it's a numeric.

    /**
     * @param $value
     * @return mixed
     */
    protected function transformNumeric($value)
    {
        if (is_numeric($value))
        {
            return '+' . $value;
        }
    }
    

    + is a javascript hack to convert string to numeric.

    opened by Freyskeyd 6
  • Alias Loading in the ServiceProvider

    Alias Loading in the ServiceProvider

    I think it's a bad practice to load the Alias inside of the ServiceProvider because some people will want or need a different name.

    Since you need to register the ServiceProvider anyways, it wouldn't be too much work adding the alias too thought.

    How do you think about it? I'd love to see this and further packages (?) without this Auto-Alias-Loading :-)

    Best Regards, hettiger.

    Btw: Thank you for Laracasts!

    opened by hettiger 6
  • Laravel 5.1.24 (LTS) variable is undefined

    Laravel 5.1.24 (LTS) variable is undefined

    I've gone through the process of setting this up multiple times but the end result is nothing each time. window.varName undefined. Other solved issues haven't worked, any help would be greatly appreciated.

    Laravel Framework version 5.1.24 (LTS)

    //composer.json
    
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*",
        "laracasts/utilities": "^2.1"
    }
    
    //app.php
    
     'providers' => [
        ...
        App\Providers\RouteServiceProvider::class,
        'Laracasts\Utilities\JavaScript\JavaScriptServiceProvider',
     ]
    
    'aliases' => [
        ...
        'View'      => Illuminate\Support\Facades\View::class,
        'JS'        => Laracasts\Utilities\JavaScript\JavaScriptFacade::class,
    ]
    
    //javascript.php
    
    return [
        'bind_js_vars_to_this_view' => 'home',
        'js_namespace' => 'window'
    ];
    
    
    //controller
    
    <?php
    
     namespace App\Http\Controllers;
    
     use App\Theater;
     use App\Http\Controllers\Controller;
     use Illuminate\Http\Request;
     use JavaScript;
    
     class NavigationController extends Controller
     {
        /* Load the home page without geolocation activated */
        public function indexWithoutGeoLocation(){
           $theaters = Theater::get();
    
         \JavaScript::put([
           'complexName' => 65
         ]);
    
      return view('home',[
        'theaters' => $theaters
      ]); 
    }
    

    my view is located at resources/views/home.blade.php and is a full view (no yields or includes) from <html> to </html>

    If functionality is relevant, I'm returning a PHP instance of $theaters to render a default page, and a JS version of theaters to update the page afterwords via AJAX.

    I have tried adding a facade manually by adding 'JS' => Laracasts\Utilities\JavaScript\JavaScriptFacade::class as suggested in https://github.com/laracasts/PHP-Vars-To-Js-Transformer/issues/58 but this did nothing.

    Additionally I have tried and failed to use \JavaScript::put() instead of JavaScript::put()

    opened by AlexeiDarmin 5
  • Not working laravel 5.4 mac with valet?

    Not working laravel 5.4 mac with valet?

    So I just have a freshly installed project with laravel valet, using laravel 5.4. Running the following commands in the exact order.

    npm install
    composer require laracasts/utilities
    php artisan vendor:publish
    

    Now I edit the config/app.php and add

    'Laracasts\Utilities\JavaScript\JavaScriptServiceProvider'
    

    to the end of the list.

    Next I edit my routes/web.php to do a quick test and edit it to the following

    use Javascript;
    Route::get('/', function () {
        Javascript::put([
            'foo' => 'bar',
            'user' => 'My sweet user',
            'age' => 29
        ]);
        return view('welcome');
    });
    

    Now I also published the config and edited it to run on the welcome page instead of the footer.

    Now I get the following error:

    The use statement with non-compound name 'Javascript' has no effect
    
    opened by jesseyofferenvan 4
  • Not working with redirects.

    Not working with redirects.

    I am trying to put the authenticated user's role to access it from angular front end. So in my AuthController

    if ($this->auth->attempt(['email'=>$email, 'password' =>$password, 'status'=>'active'],$request->has('remember')))
    {
        $user = $this->auth->user();
        JavaScript::put(['user' =>$user]);
        return redirect()->intended($this->redirectPath()); //doesn't work
        //But if I return view instead of a redirect as below it works
        return view('home'); //it works
    }
    

    What should I do to make it work with a redirect?

    opened by neeravp 4
  • Doesn't work with objects

    Doesn't work with objects

    $browserData = new stdClass; JavaScript::put(['browserData' => $browserData]);

    Gives the following error: "The provided object needs a __toString() method". Converting the object to an array fixes this problem

    opened by papa-smurf 4
  • Alias Forcing?

    Alias Forcing?

    Is there a reason why you are forcing the alias on people? In https://github.com/laracasts/PHP-Vars-To-Js-Transformer/blob/master/src/Laracasts/Utilities/UtilitiesServiceProvider.php#L39 you forcefully alias the class. Would it not be a better idea to give the user a choice to alias it themselves?

    opened by GrahamCampbell 4
  • Proposed fix for #140

    Proposed fix for #140

    After the JS has been echo'd to the blade template, remove the event listener. Appears to work in our Laravel application as well as with Octane and works with multiple binds in a single request.

    Fixes #140

    opened by jeremy-smith-maco 0
  • Occasionally sets previous variables using Laravel Octane

    Occasionally sets previous variables using Laravel Octane

    We are using Laravel Octane and it will sometimes put the previous request's variables into the current request. Putting a breakpoint in the LaravelViewBinder class, it will get hit multiple times with the same variables or with other variables from the previous request which are no longer valid for the current request.

    I am not sure what is causing it but I am guessing something is cached in the Octane instance which is not refreshing. I am not sure how to get around it either, other than manually doing the JS parsing myself.

    opened by jeremy-smith-maco 0
  • Can't get to work in Laravel 8.

    Can't get to work in Laravel 8.

    I'm not sure I'm doing this correctly. I am trying to pass data from a Vue modal to a view, not the other way around.

    I have added this to my controller after saving the new record:

        JavaScriptFacade::put([
            'customer' => $customer,
            'contact' => $contact,
        ]);
    

    The modal window then closes, but I can't find the data.

    Here are my changes to config\javascript.php:

    'bind_js_vars_to_this_view' => 'dashboard/shared/footer',

    opened by airliajsmith 1
  • Freezing the global object

    Freezing the global object

    I like the library and it solves some of my issues, though I've noticed there is a security issue with (understandably) setting the namespace object to the window by default.

    AFAIK there's no way to currently make the object immutable, which exposes the apps using the library for data manipulation of the global object being modified.

    Would that be worth adding a deep freeze functionality to prevent potential exploitation of the data being passed down to the document?

    Thanks

    opened by shaysegev 0
  • only add js (checked by hash) once

    only add js (checked by hash) once

    This solves issue https://github.com/laracasts/PHP-Vars-To-Js-Transformer/issues/110

    Queued tasks add the JS code multiple times. The fix keeps track of each js that is to be added with an array with hashes in the $view data. If there already is a hash for the js code, skip it. It seems todo the trick.

    It's not really a solution to the problem that the queue is adding multiple (unnecessary) listeners, but it is a failsafe.

    opened by morksinaanab 0
Releases(3.2.1)
Laravel Javascript Validation

Laravel Javascript Validation Laravel Javascript Validation package allows to reuse your Laravel Validation Rules, Messages, FormRequest and Validator

Proengsoft 987 Nov 25, 2022
A Blade directive to export variables to JavaScript

A Blade directive to export variables to JavaScript This package contains a Blade directive to export values to JavaScript. Here's an example of how i

Spatie 545 Dec 2, 2022
Use your Laravel named routes in JavaScript

Ziggy – Use your Laravel routes in JavaScript Ziggy provides a JavaScript route() helper function that works like Laravel's, making it easy to use you

Tighten 3k Nov 26, 2022
Html Minifier adalah paket simpel untuk minify output Html, Css style, dan Javascript sebelum dirender ke browser untuk aplikasi Laravel anda.

Laravel Html Minifier Adalah Paket simpel untuk minify HTML, Css Style, dan Javascript sebelum dirender ke browser untuk aplikasi Laravel anda. Alat i

:D 16 Aug 17, 2022
Use your Laravel named routes in JavaScript

Ziggy – Use your Laravel routes in JavaScript Ziggy provides a JavaScript route() helper function that works like Laravel's, making it easy to use you

Tighten 3.1k Dec 5, 2022
A powerful and delightful PHP WebShell

Rome WebShell A powerful and delightful PHP WebShell This is a lightweight PHP webshell, using only vanilla JavaScript and CSS, no jQuery/Bootstrap bl

Caesarovich 23 Nov 12, 2022
Tiny PHP lib to transform a number into french words.

Number To FR Words English I've written this tiny library to easily transform a number into french words. This project came up when I had to automatic

sicaa 6 Apr 27, 2022
Transform your WordPress site into a modern GraphQL server: graphql-api.com.

GraphQL API for WordPress Transform your WordPress site into a modern GraphQL server: graphql-api.com. This plugin is the implementation for WordPress

GraphQL API 152 Nov 29, 2022
Yclas Self Hosted is a powerful script that can transform any domain into a fully customizable classifieds site within a few seconds.

Yclas 4.4.0. Description Yclas self-hosted is a powerful script that can transform any domain into a fully customizable classifieds site within a few

Yclas 299 May 29, 2022
Melek Berita Backend is a service for crawling data from various websites and processing the data to be used for news data needs.

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Chacha Nurholis 2 Oct 9, 2022
📦 An easy way to share the data from your backend to the JavaScript.

Laravel Shared Data ✨ Introduction Laravel Shared Data provides an easy way to share the data from your backend to the JavaScript. ?? Quick start Inst

Coderello 326 Nov 30, 2022
ATK Data - Data Access Framework for high-latency databases (Cloud SQL/NoSQL).

ATK Data - Data Model Abstraction for Agile Toolkit Agile Toolkit is a Low Code framework written in PHP. Agile UI implement server side rendering eng

Agile Toolkit 255 Nov 14, 2022
Easy to use cryptographic framework for data protection: secure messaging with forward secrecy and secure data storage. Has unified APIs across 14 platforms.

Themis provides strong, usable cryptography for busy people General purpose cryptographic library for storage and messaging for iOS (Swift, Obj-C), An

Cossack Labs 1.6k Nov 25, 2022
A minimalist, open source online pastebin where the server has zero knowledge of pasted data. Data is encrypted/decrypted in the browser using 256 bits AES.

Current version: 1.3.5 PrivateBin is a minimalist, open source online pastebin where the server has zero knowledge of pasted data. Data is encrypted a

null 4.5k Dec 6, 2022
A simple page view counter that store data as text and shows data as a PNG image

Image Counter A simple page view counter that store data as text and shows the counter as a PNG image.

Victor Ribeiro 10 Apr 19, 2022
Data visualization for NASA's DSNNow public data

DSN Monitor Data visualization for NASA's DSNNow public data. A live version of the project can be accessed at http://dsnmonitor.ddns.net. Description

Vinz 2 Sep 18, 2022
A simple program to query mysql data and display the queried data in JSON format

A simple program to query mysql data and display the queried data in JSON format. The data displayed in JSON format will change and update as the data in your mysql database changes.

null 2 Mar 7, 2022
DataLoaderPhp is a generic utility to be used as part of your application's data fetching layer to provide a simplified and consistent API over various remote data sources such as databases or web services via batching and caching.

DataLoaderPHP is a generic utility to be used as part of your application's data fetching layer to provide a simplified and consistent API over various remote data sources such as databases or web services via batching and caching.

Webedia - Overblog 185 Nov 3, 2022