To use datatables in Laravel, you can follow these steps:
- Install DataTables using npm or yarn:
npm install datatables.net --save
- Include the DataTables CSS and JS files in your layout file:
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
- Create a route to fetch the data from the database:
Route::get('/data', function () {
return Datatables::of(User::query())->make(true);
});
- Create a view to display the data:
<table id="users-table">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Created At</th>
<th>Updated At</th>
</tr>
</thead>
</table>
<script>
$(function() {
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: '/data',
columns: [
{ data: 'name', name: 'name' },
{ data: 'email', name: 'email' },
{ data: 'created_at', name: 'created_at' },
{ data: 'updated_at', name: 'updated_at' }
]
});
});
</script>
This example assumes you have a users table in your database with name, email, created_at, and updated_at columns.
Note that this example uses the Yajra DataTables package, but you can use any other DataTables package or library if you prefer.