How to use datatables plugin in laravel?

Member

by jasen , in category: PHP CMS , a year ago

How to use datatables plugin in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , a year ago

@jasen 

To use the DataTables plugin in Laravel, you can follow these steps:

  1. Install the DataTables plugin using npm or yarn:
1
2
npm install datatables.net
npm install datatables.net-bs4


  1. Include the DataTables CSS and JS files in your layout file (e.g., app.blade.php):
1
2
3
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.25/css/dataTables.bootstrap4.min.css">
<script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.25/js/dataTables.bootstrap4.min.js"></script>


  1. Initialize the DataTables plugin in your Blade view file (e.g., users.blade.php):
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<table id="users-table" class="table">
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Created At</th>
        </tr>
    </thead>
</table>

<script>
$(document).ready(function() {
    $('#users-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: '{{ route('users.data') }}',
        columns: [
            { data: 'name', name: 'name' },
            { data: 'email', name: 'email' },
            { data: 'created_at', name: 'created_at' }
        ]
    });
});
</script>


  1. Create a route in your routes/web.php file to handle the AJAX request for data fetching:
1
Route::get('users/data', 'UserController@getData')->name('users.data');


  1. In your UserController.php file, create a method to fetch user data from the database and return it as JSON for DataTables to display:
1
2
3
4
5
6
public function getData()
{
    $users = User::select(['name', 'email', 'created_at']);
    
    return Datatables::of($users)->make(true);
}


  1. Make sure you have a UserController and a User model set up in your Laravel application.


That's it! You should now have the DataTables plugin integrated into your Laravel application. You can customize the DataTables plugin further by adding additional options and features as needed.

Related Threads:

How to use barcode scanner with datatables laravel?
How to export datatables in multiple tabs in laravel?
How to use chosen jquery plugin on laravel?
How to use vite plugin with storybook?
How to use elementor plugin in webstorm?
How to restrict a user to use only one plugin in wordpress?