In this tutorial we will learn how to use datatable in laravel.
How to use Datatable in Laravel
Step 1 - Install the Package: First, you need to install the Datatable package using Composer. You can do this by running the following command in your terminal:
composer require yajra/laravel-datatables-oracle
Step 2 - Create a Route: Next, you need to create a route in your routes/web.php file that will handle the Datatable request. For example:
Route::get('/users', 'UserController@getUsers')->name('users');
Step 3 - Create a Controller: Create a new controller called UserController that will handle the request and fetch the data from your database. For example:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use DataTables;
class UserController extends Controller
{
public function getUsers(Request $request)
{
$users = User::select(['id', 'name', 'email', 'created_at']);
return DataTables::of($users)->make(true);
}
}
Step 4 - Create a View: Create a new view that will display the data table. For example:
<table id="users-table" class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Created At</th>
</tr>
</thead>
</table>
<script>
$(function() {
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('users') !!}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
{ data: 'email', name: 'email' },
{ data: 'created_at', name: 'created_at' }
]
});
});
</script>
In this view, we're using jQuery and the Datatable library to create the data table. We're also setting the ajax option to the route that we created in step 2.
That's it! Now, when you navigate to /users in your application, you should see a data table with the data from your users table. The Datatable package will handle pagination, searching, and sorting of the data table automatically.