Laravel Server-Side DataTable with Persistent Checkbox Selection and Select All Option
Laravel me server-side DataTable kaise implement karte hain with checkbox selection, jisme ‘Select All’ option ho aur wo pagination, search aur filtering ke baad bhi persist kare?
1. HTML Table
<table id="resourcesDataTable" class="table table-striped table-bordered" cellspacing="0" width="100%" >
<thead>
<tr>
<th class="text-center"><input type="checkbox" id="allResources" value="1"></th>
<th>Title</th>
<th>Grade</th>
<th>Unit</th>
<th>File Name</th>
<th class="text-center">Date</th>
<th class="text-center">Action</th>
</tr>
</thead>
</table>
👉 Yeh ek DataTable structure hai jisme:
- Pehla column checkbox ke liye (individual select aur select all option ke liye).
- Title, Grade, Unit, File Name, Date aur Action columns.
2. Controller: getResourcesList()
public function getResourcesList(Request $request)
{
$query = Resources::with(['gradeTitle', 'unitTitle'])
->where('status', 1)
->orderBy('sortorder', 'ASC');
return datatables()->of($query)
->addColumn('checkbox', function ($resource) {
return '<input type="checkbox" name="resourceIds[]" class="resourceCheckbox" value="'.$resource->id.'">';
})
->addColumn('grade', function ($resource) {
return $resource->grade_id == 0 ? 'All Grade' : $resource->gradeTitle->title;
})
->addColumn('unit', function ($resource) {
return $resource->unit_id == 0 ? 'All Unit' : $resource->unitTitle->title;
})
->addColumn('date', function ($resource) {
return \Carbon\Carbon::parse($resource->created_at)->format('m/d/Y h:i A');
})
->addColumn('action', function ($resource) {
if ($resource->file_name) {
return '<a href="/resource/'.$resource->id.'/download" class="download" title="Download">
<i class="fa fa-download"></i>
</a>';
}
return '-';
})
->rawColumns(['checkbox', 'action'])
->make(true);
}
👉 Yaha backend query banti hai:
- Resources table se data fetch ho raha hai.
- Extra columns ban rahe hai (checkbox, grade, unit, date, action).
- Carbon se date format change ho rahi hai.
- Agar file hai to download link dikhega, warna
-.
3. Frontend DataTable Initialization
var table = $('#resourcesDataTable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('getResourcesList') }}",
columns: [
{ data: 'checkbox', name: 'checkbox', orderable: false, searchable: false, className: 'text-center' },
{ data: 'title', name: 'title' },
{ data: 'grade', name: 'grade' },
{ data: 'unit', name: 'unit' },
{ data: 'file_name', name: 'file_name' },
{ data: 'date', name: 'date', className: 'text-center' },
{ data: 'action', name: 'action', orderable: false, searchable: false, className: 'text-center' }
],
order: [],
pageLength: 10,
language: {
emptyTable: "No data found",
lengthMenu: '_MENU_ rows per page'
}
});
👉 Yeh DataTable ko server-side banata hai:
- Data Ajax se load hoga Laravel route
getResourcesListse. - Checkbox column ko search/order disable kiya gaya hai.
- Pagination, sorting, searching sab DataTable handle karega.
4. Checkbox Selection Logic
var selectedResource = new Set(); // sab selected resources yaha store honge
var isAllSelected = false;
function updateSelectAllCheckbox() {
let totalChecked = selectedResource.size-1;
let totalVisible = $('#resourcesDataTable').DataTable().page.info().recordsDisplay;
if (totalVisible > 0 && totalVisible === totalChecked) {
$('#allResources').prop('checked', true);
} else {
$('#allResources').prop('checked', false);
isAllSelected = false;
}
}
👉 Yeh function check karta hai:
- Agar jitne records screen pe visible hai utne hi select hue hai → select all box auto check ho jaaye.
- Agar kuch deselect ho gaya → select all uncheck ho jaaye.
5. Select All Checkbox Event
$('#allResources').on('change', function () {
const isChecked = $(this).is(':checked');
if (isChecked) {
$.get('/ajax-getAllResource-ids', function (allIds) {
isAllSelected = true;
allIds.forEach(id => selectedResource.add(String(id)));
$('.resourceCheckbox').each(function () {
const id = $(this).val();
$(this).prop('checked', true);
});
updateSelectAllCheckbox();
});
} else {
isAllSelected = false;
selectedResource.clear();
$('.resourceCheckbox').prop('checked', false);
updateSelectAllCheckbox();
}
});
👉 Jab user select all checkbox click kare:
- Agar check kiya → backend se sabhi resource IDs leke set me daal do.
- Sab visible checkboxes ko bhi tick karo.
- Agar uncheck kiya → sab clear.
6. Individual Checkbox Event
$(document).on('change', '.resourceCheckbox', function () {
const id = $(this).val();
if ($(this).is(':checked')) {
selectedResource.add(id);
} else {
selectedResource.delete(id);
}
updateSelectAllCheckbox();
});
👉 Agar ek ek karke checkbox tick/untick kiya:
- Set me ID add/remove ho jaayegi.
- Select all ka state bhi update ho jaayega.
7. Table Draw Event
table.on('draw', function () {
$('.resourceCheckbox').each(function () {
const id = $(this).val();
$(this).prop('checked', selectedResource.has(id));
});
updateSelectAllCheckbox();
});
👉 Jab DataTable refresh / next page / search karega:
- Already selected checkboxes ko dobara check kar dega.
- Select all ka state bhi sync ho jaayega.
8. Backend for Select All IDs
public function getAllResourceIds(Request $request)
{
$ids = Resources::query()->pluck('id');
return response()->json($ids);
}
👉 Yeh ek API endpoint hai jo saare resource IDs bhej deta hai.
Select all ka logic isi ke through chal raha hai.
🔑 Summary
- DataTable server side load ho raha hai.
- Har row ke saath checkbox diya gaya hai.
selectedResourceek Set object hai jo selected IDs store karta hai.- Select All click karne par → backend se sabhi IDs fetch hote hai aur sab select ho jaate hai.
- Page change / search / reload hone par → already selected items dobara check ho jaate hai.
- Ye pura system ek persistent checkbox selection deta hai DataTable me.
Leave a Reply