I'm using yajra's datatables on Laravel 8, trying to implement "default sorting" on the server-side. It's already working, but I'm trying to find other solutions because the implementation feels a bit hacky.
I have something like this in my controller:
$myData = new MyData;
if ($request->order[0]['column'] === '0') {
$myData->orderBy('priority');
}
return DataTables::of($myData)->make(true);
Please notice the if ($request->order[0]['column'] === '0')
part. The idea here is that if the table is initiated for the first time, alias users haven't made any column sorting by themselves, then the data should be sorted by whatever is defined inside the if-statement. The datatables itself doesn't have a defined order
property, thus the sorting is given to column 0
by default.
I'm doing the sorting from the server-side because it's a bit complicated and will be easier to be done from the server rather than datatables. Once again, the code above IS working, but I just feel that this is a bit hacky. Is there any other alternatives I can use? Should I change the code, or is this alright?
So in your blade code on the front add this to your function to fill the datatable...
order: [],
This will tell datatables to not do any sorting of the data and use what you give it as the first sort order. Basically giving it an empty array. Then you can get rid of the condition totally. Then just sort your data like you normally would in your eloquent collection you are making to fill said datatable. Here is the documentation for this: https://datatables.net/reference/option/order