Laravel pass data from controller to javascript
I want to pass data from my Controller to a JavaScript that handles a Google Bar Chart. composer
from my
.js file:
the 2nd bar from Google-Bar-Chart is blank .... But there should be displayed my variable. How do I solve this issue? In this tutorial I will show you how to send value from controller to Javascript in Blade in Laravel application. Say you have a value $x=10 in your controller and you want to grab the value in your blade. Then do the following steps to get the value in front end code. 1. Send the value using compact function to blade like below
2. Now in your javascript retrieve the value like below
I hope you got it and you can do it this way.... View Discussion Improve Article Save Article View Discussion Improve Article Save Article Laravel provides different ways to pass data to a view. We can pass data directly from routes or through the controller. Here are some of the ways we can pass data to the view:
1. Using view(): We can directly pass the data in the ‘view()’ helper function by using the second parameter in the function which takes an array as key and value pair. Note: Comment or delete any previous route in the ‘web.php’ file in ‘routes’ directory. Example 1:
Output: Example 2: We can pass an array with multiple values also.
Output: 2. Using with(): The ‘with()’ is a method to pass individual form of data and is used with the ‘view’ helper function. Example:
Output: 3. Using compact(): The ‘compact()’ is a PHP function that can be used for creating an array with variable and there value. Here the name on the variable is the key and the variable content is the value. Note: Comment or delete any previous route in the ‘web.php’ file in ‘routes’ directory. Example:
4. Using Controller Class: Passing data using controller class is easy and is the right way. Example:
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. |