In this small article, I will let you know how to pass a variable to jquery in laravel. We always require to get data from laravel model eloquent and pass that variable to javascript.
We almost require to pass array variable to javascript in laravel like calender, chart, google map etc. So when you require to print php variable in js then you can do it easily.
Here, i will simple get all users from User model then i will simple assign to users variable of jquery. So i want to just share with you controller method and how you can access that variable in jquery.
Controller Method:
public function index()
{
$users = User::get();
return view('users.index', compact('users'));
}
Access Variable to JS:
<script type="text/javascript">
var users = {!! json_encode($users->toArray()) !!};
console.log(users);
</script>
I hope you got it and you can do it this way....
Do you like below Tutorials ?
- How to Display Data in Angular 10?
- Angular 10 Routing Module Example Tutorial
- Angular 10 CRUD Operations with Web API Example
- Laravel 8 CRUD Operation Step By Step Tutorial
- Solved - Target class [ProductController] does not exist in Laravel 8
- Step by Step Form Validation in Laravel 8 Example
- Laravel 8 Image Upload with Preview Example
- Laravel 8 Multiple Images Upload with Preview Example