DEV Community

Cover image for DataTables tips using Laravel
Surya Wiguna
Surya Wiguna

Posted on

DataTables tips using Laravel

Datatable is a useful plugin for displaying data to table in more advance way. It provide search, filter, pagination, and sorting from the beginning you use it. But you usually don't need all of the feature, or want to display button in the table, etc. Now I wanna share some tips in using datatable with Laravel.

Add button inside datatable

When displaying data in a row, usually in the last column we want to add button for user to take action with the data e.g. button edit, and delete. But datatable not natively render html tag, so we need to use addColumn() and rawColumns() like this in controller:

$data = DataTables::of($data)->addColumn('action', function($row) {
   return "<a href='/user/edit/1' class='btn btn-sm btn-success'>Edit</a><a href='/user/destroy/1' class='btn btn-sm btn-danger btn-delete'></i>Hapus</a>";
})->rawColumns(['action']);
Enter fullscreen mode Exit fullscreen mode

Load table on click

This case is usually when you have multiple datatable in one page and you organize it in tab view, you want to load data only when related tab is click. You can reload the table by using reload() function to do that.

$('#clickable_id').click(function() {
  $('#table').DataTable().ajax.reload();
});
Enter fullscreen mode Exit fullscreen mode

Disable Sorting and searching individual column

Datatable provide many feature to make a more useful table like searching, pagination, sorting, etc. But when you don't want particular column searchable or sortable, you can disable it.

columns: [
   { data: 'name', searchable: false, orderable: false },
]
Enter fullscreen mode Exit fullscreen mode

That are some tips to use datatable with Laravel. Thank you for reading, if you have any more tips or question please drop it on discussion section.

Top comments (0)