Laravel pass variable to javascript
is there any ways that JavaScript can get the variable from the controller in a Laravel Blade template? Show Example: I have the code below:
Can I get This is my create function in the controller:
this is my view:
my javascript.php in config folder:
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 JavaScriptPhoto by KOBU Agency on UnsplashIn Laravel, we
pass the data to the Blade view using the Passing Data To ViewsIn the application route, the second argument is used to pass the data to view. Route::get('/', function () { 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 public function show(Permission $permission) Pass a PHP Variable to JavaScriptBut 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. Without package: Using JSON RenderingIn Laravel Rendering JSON will be used to initialize a JavaScript variable. ExampleNow add the array data in the application route. This page_data array we need to use as JavaScript. Route::get('/', function () { Add the below Js::from in the welcome view
open the browser and check the page_data in the console. 2. Using Transform PHP Vars to JavaScript packageInstall the package through Composer composer require laracasts/utilities Add the package to the provider
'providers' => [ Create HomeController and call the welcome view
namespace App\Http\Controllers;use App\Http\Controllers\Controller;
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
You can change the footer view by publishing the default configuration. Then update the ‘bind_js_vars_to_this_view’ config value on php artisan vendor:publish --provider="Laracasts\Utilities\JavaScript\JavaScriptServiceProvider"
@include ('footer') // <-- Variables prepended to this view Now the title and price are available on the window object. 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. |