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 Open URL in New Tab using Jquery?
- Laravel 7.x and 6.x Routing Tutorial
- Ng Bootstrap Modal in Angular 8 Example
- Bootstrap 4 Datepicker in Angular 9/8 Example
- Disable Registration Route in Laravel
- Bootstrap Timepicker in Angular Example
- Count Number of Pages in PDF - PHP Script
- Digital Signature PHP Script Example