0

I'm using Datatables on my Laravel project to show stock of products, but when I tried to sort it, it's error

This is my script in view

@section('script')
    <script type="text/javascript">
        $(function () {
            var oTable = $('#stock-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: '{{ url("stock-data") }}'
                },columns: [
                    {data: 'updated_at', name: 'updated_at'},
                    {data: 'product_name', name: 'product_name'},
                    {data: 'unit_stock', name: 'unit_stock'},
                    {data: 'status', name: 'status'},
                ],
            });
        });
    </script>
@endsection

And this is my controller

public function stock()
    {
        return view('stock-report');
    }

    public function stockData()
    {
        $stock = Products::all();
        return Datatables::of($stock)
//            ->orderColumn('unit_stock $1')
            ->addColumn('status', function ($stock) {
                if ($stok->unit_stock == 0)
                    return '<span class="label label-danger">EMPTY</span>';
                else
                    return '<span class="label label-success">NOT EMPTY</span>';
            })
            ->make(true);
    }

It's error when I add ->orderColumn('unit_stock $1'), is there any solution, big thanks

3
  • It would help if you posted the error. You could probably find this by using developer tools and checking the response or in your laravel.log file. Commented May 11, 2017 at 10:21
  • It says DataTables warning: table id=tabel-stok - Ajax error. For more information about this error, please see http://datatables.net/tn/7 Commented May 11, 2017 at 10:35
  • If you go to datatables.net/tn/7 and go to diagnosis it will show you how to see the actual error. This assumes you have debug set to true in your .env file, otherwise the error should be in your laravel log file. Commented May 11, 2017 at 10:39

1 Answer 1

1

try to sort the Datatable adding : order

$('#stock-table').DataTable( {
.
.
.
       "order": [[ numberColum, "desc" ]],
.
.
} );

also you can try to order in the select:

Products::orderBy('unit_stock', 'DESC')->get();
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much it works, I've been using Products::orderBy('unit_stock', 'DESC')->get(); but the result just sorting the first data and the next one is randomize

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.