How to add row number or Serial no in laravel datatable
If you are using yajra laravel datatables
Just add ->addIndexColumn()
return DataTables::of($data)
->addIndexColumn()
->make(true);
In your javascript, you can set the first row as a serial number like this
columns: [
{ data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false },
{ data: 'name', name: 'name' },
{ data: 'action', name: 'action' }
]
use DT_Row_Index instead of DT_RowIndex for older yajra datatable version
When using Yajra Laravel datatables
return DataTables::of($result)
->addIndexColumn()
->make(true);
"columns": [
{
"data": 'DT_RowIndex',
orderable: false,
searchable: false
},
]
Set the variable rownum at the beginning of your query. Then set the increment process in your query.
DB::statement(DB::raw('set @rownum=0'));
$data = BillInfo::get(['bill_info.*',
DB::raw('@rownum := @rownum + 1 AS rownum')]);
return Datatables::of($data)
->removeColumn('id')
->make(true);
Here you can get rownum as serial no of the given records [1 . . . 8].
In Laravel Yajra Datatables v9.x as Service Implementation, I add this in getColumns function and works well in sorting, searching, and page changing.
'id' => ['title' => 'N.', 'orderable' => false, 'searchable' => false, 'render' => function() {
return 'function(data,type,fullData,meta){return meta.settings._iDisplayStart+meta.row+1;}';
}],