Search code examples
laraveldatatableyajra-datatable

How to limit results per page in Yajra datatables


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?


Solution

  • 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).