hendraspt hendraspt - 7 months ago 143
PHP Question

How to display data on datatables using laravel 5?

I am using laravel 5 and I want to show field in jenis_surat column in database to my table using datatables. I want to using JSON, do you know how to show the number depends on the entries of the data.
here is my controller (It's just shows data in jenis_surat):

public function jenissurat()
{return view('jenissurat');}

public function datajenissurat()
{
$jenissurat = new JenisSurat();
$jenissurats = $jenissurat->select('jenis_surat')->get();
return $jenissurats;
}


And how to display it on datatables? example:

No. Jenis Surat. .Action
1. . .A . . . . . . . . . Edit | Delete
2. . .B . . . . . . . . . Edit | Delete
3. . .F . . . . . . . . . Edit | Delete


<table id="publish" class="table table-bordered table-striped" cellspacing="0" widht="100%">
<thead>
<tr>
<th width="4%">No.</th>
<th width="80%">Publish</th>
<th width="16%">Action</th>
</tr>
</thead>
</table>
<script type="text/javascript">

$(document).ready(function(){
$('#publish').DataTable({
'columns' : [
{'data' : 'publish'}
]
});
});

</script>

Answer

Try this, I am not sure this is a best solution from the performance point of view.

public function jenissurat()
 {
    $returnValue = $this->datajenissurat();
    return view('jenissurat', compact('returnValue'));
 }

 public function datajenissurat()
 {
    $jenissurat = new JenisSurat();
    DB::statement(DB::raw('set @rownum=0'));

    $jenissurats = $jenissurat->select([DB::raw('@rownum  := @rownum  + 1 AS rownum'), 'jenis_surat'])->get();   
    return $jenissurats;
 }

And regarding to the Datatables you can add something like this.

  <script>
    var table_previous_link = '#jobs-table_previous';
    $(function() {

       var oTable = $('#publish').DataTable({
           bProcessing    : true,
           serverSide     : true,
           /* sDom           : 'p', */
           dom            : 'Bfrtip',
           ajax: {
           url: '{!! route("your.route.to.datajenissurat") !!}',
           data: function (d) {

           }
        },        
      columns: [
        { data: 'rownum', name: 'rownum' ,orderable: false, searchable:  false },
        { data: 'jenis_surat', name: 'jenis_surat' },
        { data: 'action', name: 'action', orderable: false, searchable:  false }
        ]
     });
   });
  </script>

I see a edit/delete column that can be used by the action column. So, the ajax call to your controller function datajenissurat() will return a json array, which can be parsed using the datatable script.

Comments