jim1506's avatar

Datatables from a raw Query

I have a datatable in a view that is server processing as the table has several thousand records. I have attempted to use eloquent to get the data but by faw the easiest is a raw SQL.

My view is

 <table id="thetable" class="table table-striped table-bordered" width="90%" align="center" cellspacing="5px" cellpadding="10px" >
        <thead>
        <th>ID</th>
        <th>PartNo</th>
        <th>Description</th>
        <th>ManufacturerName</th>       
        <th>accountcode</th>
        
        </thead>
    </table>
</div>
<script>
     $('#thetable').DataTable({
                dom: 'lBfrtip',
                "iDisplayLength": 30,
                "lengthMenu": [ 10, 25,30, 50, 75, 100,200 ],
                buttons: [
                    'copy',  'print',
                    {extend: 'excel',
                        filename: 'PartDetails', footer:true},
                    {extend: 'pdf',
                        filename:  'PartDetails'},
                    {extend:'csvHtml5',
                        filename: 'PartDetails'},
                    {extend: 'collection',
                        text: 'columns',
                        buttons:['columnsVisibility'] }
                ],
                processing: true,
                serverSide: true,
                ajax: 
                    {url: ' {{ route('partdetails.serverSide') }}',
                    type: 'GET' }
                }) ;
 </script>

My data is supplied by

Route::get('/partdetails/serverSide',[
    'as' => 'partdetails.serverSide',
   'uses' => function(){
        $parts = DB::select('SELECT partdetails.ID, partdetails.PartNo, partdetails.Description, manufacturer.Manufacturer AS ManufacturerName, partdetails.accountcode FROM partdetails INNER JOIN manufacturer ON partdetails.Manufacturer = manufacturer.entry ORDER BY partdetails.PartNo ASC');
        return Datatables::of($parts)->make();
    }

If I dd the $parts it is all correct and myh columns in datatables are perfectly correct but I get an ajax error which is

DataTables warning: table id=thetable - Ajax error. For more information about this error, please see http://datatables.net/tn/7

The table and the names are perfectly correct. Is this something because I am using DB select?

Thanks...

0 likes
5 replies
yajra's avatar

@jim1506, I think DB::select() returns an array and thus you need to convert it to collection first.

collect(DB::select('sql'))

Anyways, I think plain array should be accepted as data source and thus will enhance the package to support it.

You can track the progress here: https://github.com/yajra/laravel-datatables/pull/992

Thanks!

1 like
geetugipson's avatar

i am also experiencing the same issue . How can i rectify it?

Please or to participate in this conversation.