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
Configuration
- write in the composer or terminal (hold shift+right click on your project)
1 |
composer require laracasts/utilities |
- Go to composer.json(check following line or add if you haven’t)
1 2 3 |
"require": { "laracasts/utilities": "^3.0", }, |
-
Go to config/app.php
in provider, add following line
1 |
Laracasts\Utilities\JavaScript\JavaScriptServiceProvider::class, |
in aliases, add following line
1 |
'JavaScript'=>Laracasts\Utilities\JavaScript\JavaScriptFacade::class, |
- write in composer
1php artisan vendor:publish
This will add a new configuration file to config/javascript.php - by default, in config/javascript.php
12345678<?phpreturn ['bind_js_vars_to_this_view' => 'footer','js_namespace' => 'window'];
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
1 2 3 4 5 6 7 |
<?php return [ 'bind_js_vars_to_this_view' => 'footervarview', 'js_namespace' => '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
1 |
use JavaScript; |
- Add inside controller function
1 2 3 |
JavaScript::put([ ]); |
Suppose the controller look like (PatientController .php)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use JavaScript; class PatientController extends Controller { // public function view_patient(){ $dataname='today is holiday'; //following line sent or pass these variables direcly to js area JavaScript::put([ 'testname'=>'bonstutorial', 'age'=>46, 'data'=>$dataname ]); return view('patient_details'); } } |
- create a view file patient_details.bade.php
- in patient_details.blade.php , add @include(‘footervarview’)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<!DOCTYPE html> <html> <head> <title></title> </head> <body> php var js @include('footervarview') <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ console.log(windowvar.testname); console.log(windowvar.age); console.log(windowvar.data); }) </script> </body> </html> |