Datatable Example in Laravel using Ajax

AuthorSumit Dey Sarkar

Pubish Date22 Mar 2023

categoryLaravel

In this tutorial we will learn datatable example in laravel using ajax.

 

Datatable example in laravel using ajax

Here's an example of how to use DataTables in Laravel with Ajax:

 

1) Create a route to handle the Ajax request:

Route::get('users', 'UserController@getUsers')->name('users.get');

 

2) Create a controller method to retrieve the data:

public function getUsers()
{
    $users = User::select(['id', 'name', 'email', 'created_at']);
    
    return datatables()->of($users)->toJson();
}

 

3) Create a view with the table and include the DataTables and jQuery libraries:

<!DOCTYPE html>
<html>
<head>
    <title>Users DataTable</title>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css">
</head>
<body>
    <table id="users-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Created At</th>
            </tr>
        </thead>
    </table>

    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#users-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: '{{ route('users.get') }}',
                columns: [
                    { data: 'id', name: 'id' },
                    { data: 'name', name: 'name' },
                    { data: 'email', name: 'email' },
                    { data: 'created_at', name: 'created_at' }
                ]
            });
        });
    </script>
</body>
</html>

 

4) Visit the view and you should see the table populated with data from the Ajax request.

 

Note: this example assumes you have the necessary Laravel and DataTables libraries installed and configured. You may need to adjust the code to fit your specific use case.

Comments 0

Leave a comment