To create a user list in Laravel using Yajra DataTables, you can follow these steps:
- Install Yajra DataTables: Install Yajra DataTables using Composer by running the following command in your terminal:
composer require yajra/laravel-datatables-oracle
- Create a new controller: Create a new controller by running the following command in your terminal:
php artisan make:controller UserController
- Add a method to retrieve the user data: Add a method to your UserController that retrieves the user data from your database. For example:
use App\Models\User;
use DataTables;
public function index()
{
$users = User::select(['id', 'name', 'email']);
return DataTables::eloquent($users)->toJson();
}
- Create a view for the user list: Create a new view file for your user list. For example, create a file called
users.blade.php
in yourresources/views
directory:
<html>
<head>
<title>User List</title>
<link href="//cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css" rel="stylesheet">
</head>
<body>
<table id="users-table" class="display" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
</table>
<script src="//code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="//cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
<script>
$(function() {
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: '{{ route('users.index') }}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
{ data: 'email', name: 'email' }
]
});
});
</script>
</body>
</html>
- Create a route for the user list: Create a route for your user list that points to your UserController's index method. For example:
Route::get('users', 'UserController@index')->name('users.index');
- Test your user list: Run your application and visit the
/users
route. You should see a table that displays the user data.
That's it! You now have a user list in Laravel using Yajra DataTables.
No comments:
Post a Comment