Ad

Yajra Data Tables Order By Column

- 1 answer

I'm using yajra/laravel-datatables plugin to get create datatables in laravel. This is my code.

$data = MyModel::latest()
                ->where('subject', 3)
                ->get();

return Datatables::of($data)->make(true);

This is my js code

var table = $('#empTable').DataTable({
        processing: true,
        serverSide: true,
        serverMethod: 'post',
        ajax: "{{ url('my url') }}",
        columns: [
            {data: 'reference_no', name: 'reference_no'}
        ]
    });

But unfortunately data is not sorted and I'm not getting latest data first ('id' 'desc'). It would be a great help if someone has a solution

Ad

Answer

You can overwrite the default sorting from dataTable in order to achieve the desired result:

var table = $('#empTable').DataTable({
    processing: true,
    serverSide: true,
    serverMethod: 'post',
    order: [],
    ajax: "{{ url('my url') }}",
    columns: [
        {data: 'reference_no', name: 'reference_no'}
    ]
});

By default dataTable will sort the table by the first column, so the reference_no in your case, but since you are providing the inital ordering from your data, you can set the default ordering to an empty array.

Ad
source: stackoverflow.com
Ad