Laravel pass variable to javascript

is there any ways that JavaScript can get the variable from the controller in a Laravel Blade template?

Example: I have the code below:

$langs = Language::all();
return View::make('NAATIMockTest.Admin.Language.index',compact('langs'));

Can I get $langs and pass it to JavaScript? I already used PHP-Vars-To-Js-Transformer. But when I use JavaScript::put() for two functions in the controller. It didn't work. Any help?

This is my create function in the controller:

public function create()
{
    $names = $this->initLang();
    Javascript::put([
        'langs' => $names
    ]);
    
    return View::make('NAATIMockTest.Admin.Language.create',compact('names'));
}

this is my view:

@extends('AdLayout')
@section('content')

    

Create language

{!! Form::open() !!}

{!! Form::label('Name','Language: ') !!}


{!! Form::submit('Create',['class'=>'btn btn-primary']) !!}  {!! Html::linkAction('NAATIMockTest\LanguageController@index', 'Back', null, array('class' => 'btn btn-primary')) !!}
{!! Form::close() !!}
@endsection

my javascript.php in config folder:

 'footer',
    'bind_js_vars_to_this_view' => 'NAATIMockTest.Admin.Language.create',
    'bind_js_vars_to_this_view' => 'NAATIMockTest.Admin.Language.edit',
    
    'js_namespace' => 'window',
];

The idea is: I have a table language in MySQL. I want to show the dropdown list with multiple attributes to choose, and I also want to search with angularjs as well. That's why I want to pass the variable from the controller to JavaScript. Additionally, I have the function inside LanguageController called initLang to check if any language is exist inside the database, it isn't displayed inside the dropdown list in create the view.

Transform PHP Vars to JavaScript

Photo by KOBU Agency on Unsplash

In Laravel, we pass the data to the Blade view using the view helper.

Passing Data To Views

In the application route, the second argument is used to pass the data to view.

Route::get('/', function () {
return view('welcome', ['name' => 'James']);
});

In the controller also the view helper is used to pass the data.

The “Dot” notation may be used to reference nested views. The Below permission, data will render on resources/views/admin/permission/show.blade.php

public function show(Permission $permission)
{
return view('admin.permission.show', compact('permission'));
}

Pass a PHP Variable to JavaScript

But in some cases, you want to pass some server-side var to JavaScript. For example, required some values for the analysis. We can pass variables by using the Transform PHP Vars to JavaScript package. Also, we can do by without using this package.

  • 1. Using JSON Rendering
  • 2. Using Transform PHP Vars to JavaScript package

1. Without package: Using JSON Rendering

In Laravel Rendering JSON will be used to initialize a JavaScript variable.

Example

Now add the array data in the application route. This page_data array we need to use as JavaScript.

Route::get('/', function () {
return view('welcome', ['page_data' => [
'title' => 'Home',
'price' => 20
]]);
});

Add the below Js::from in the welcome view

resources/views/welcome.blade.php

open the browser and check the page_data in the console.

Laravel pass variable to javascript

2. Using Transform PHP Vars to JavaScript package

Install the package through Composer

composer require laracasts/utilities

Add the package to the provider

config/app.php

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

Create HomeController and call the welcome view

app/Http/Controllers/HomeController.php

namespace App\Http\Controllers;use App\Http\Controllers\Controller;
use JavaScript;
class HomeController extends Controller
{
public function index()
{
JavaScript::put([
'title' => 'Home',
'price' => 20
]);
return view('welcome');
}
}

Also, update the routes/web.php to call the HomeController

Route::get('/', [HomeController::class, 'index']);

This package, by default, binds your JavaScript variables to a “footer” view. So create the empty footer blade file and include it in the welcome view

resources/views/footer.blade.php

You can change the footer view by publishing the default configuration. Then update the ‘bind_js_vars_to_this_view’ config value on config/javascript.php file.

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

resources/views/welcome.blade.php

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

Laravel pass variable to javascript

Now the title and price are available on the window object.

Laravel pass variable to javascript

If you know of any other alternative methods, share them in the comment.

Thank you for reading.

Stay tuned for more!

Follow me at balajidharma.medium.com.