Laravel Transform PHP Variable to direct JavaScript

Sometimes we need to Transform PHP Variable, array, data direct to JavaScript in Laravel. It saves to write multiple codes or lines which is not essential. Here I will show you how to do it with example.

Transform PHP Variable from controller to direct JavaScript in Laravel


  • write in the composer or terminal (hold shift+right click on your project)

  • Go to composer.json(check following line or add if you haven’t)

  • Go to config/app.php

in provider, add following line

in aliases, add following line

  • write in composer

    This will add a new configuration file  to config/javascript.php
  • by default, in config/javascript.php

    Here footer is actually the View you want your new  JavaScript variables to be prepended to.

                    window By default, all JavaScript variables will be nested under the global window object


You can change these footer and window to your desired name.
Suppose I name footer to footervarview and window to windowvar

  • create a view called footervarview.blade.php under views folder (/resources/views/footervarview.blade.php)

          Note: this view name must be same with ‘bind_js_vars_to_this_view’ => ‘footervarview’, 

This file will be totally empty...Nothing inside

How to use

  •     in the controller (PatientController .php), add the following

  • Add inside controller function

Suppose the controller look like (PatientController .php)

  • create a view file patient_details.bade.php
  • in patient_details.blade.php , add @include(‘footervarview’)

See video in youtube

Share with:

Comments are closed.