How to limit results per page in Yajra datatables

6.9k Views Asked by At

How can I limit the results of data each page in Yajra datatables? Currently I'm using the code below:

Controller

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

The $results variable is just an array of data from database.

JS

$('table.dataTableAjax').DataTable({
     "processing": true, // Make this true, to show the "Processing" word while loading
     "serverSide": true,
     "paging": true,
     "pageLength": 10,
     "ordering": false, // Make this false, to disable sorting
     "ajax": "..."
});

Example data from server

{
    "data":[
        { "name": "Bob", "Age": 30 },
        { "name": "Billy", "Age": 33 },
        { "name": "Megan", "Age": 31 }
    ]
}

So for example, the first page should load 10 rows, next page 10 rows again, and so on. But what's happening is it loads the 5000+ rows, and just cutting them into 10 table rows in client side which affects the performance of the application. Any idea?

2

There are 2 best solutions below

2
On BEST ANSWER

I ended up by just adding these code below, and not using yajra for the functionality.

$limit = request('length');
$start = request('start');

$query->offset($start)->limit($limit);

return response()->json([
    "draw" => intval(request('draw')),  
    "recordsTotal"    => intval(User::count()),  
    "recordsFiltered" => intval($total_filtered),
    "data" => $results
]);

Everything works fine, and loads faster. I didn't notice that datatables actually throws requests to the laravel end point (route).

0
On

this is working for me and shorter code

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

setTotalRecords() is a best answer for your looking for