0
votes

I'm trying to implement DataTables in Laravel, but it's not working. The table:

<table class="table table-striped" id="Clientes">
        <thead>
          <tr>
            <th>ID</th>
            <th>Nombre</th>
            <th>Domicilio</th>
          </tr>
        </thead>
        <tbody>

        </tbody>
</table>

The script:

  $(document).ready(function() {
    $('#Clientes').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": '{{ route('getClientes') }}',
        "columns": [
          {"data": 'id', "name": 'id'},
          {"data": 'nombre', "name": 'nombre'},
          {"data": 'domicilio', "name": 'domicilio'}
        ]
    } );
} );

And the route:

Route::get('/api/clientes', [
        'as'    => 'getClientes',
        'uses'  => function(){
        $clientes = Cliente::select(['id','nombre','domicilio'])->get();
        return Datatables::of($clientes)->make();}
    ]);

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

But i can't resolve the problem. Can anyone helpme ?

UPDATE

The error is: message": "Class 'Yajra\Datatables\Facades\DataTables' not found", "exception": "Symfony\Component\Debug\Exception\FatalThrowableError",

2
Maybe dumb question but did you include the 'providers' => [ ..., Yajra\DataTables\DataTablesServiceProvider::class, ] 'aliases' => [ ..., 'DataTables' => Yajra\DataTables\Facades\DataTables::class, ] in your config?Serge
Yes, i added. The problem was that the class is "DataTables", and i call "Datatables"Guido Caffa

2 Answers

0
votes

Don't use get() at the end.

Instead of

$clientes = Cliente::select(['id','nombre','domicilio'])->get();

use

$clientes = Cliente::select(['id','nombre','domicilio']);
0
votes

datatable server side View

                                <table  class="table table-striped display nowrap" id="brand">
                                    <thead class=" text-primary">
                                    <th>
                                        ID
                                    </th>
                                    <th style="width: 85%">
                                        Brand
                                    </th>

                                    <th>
                                        Active
                                    </th>
                                    </thead>
                                    <tbody style="font-size: 12px; font-weight: bold">

                                
                                    </tbody>
                                </table>
<script>
$(document).ready(function() {
    $('#brand').DataTable( {
        dom: 'Bfrltip',
        pageLength: 10,
        lengthMenu: [ 5, 10, 20, 50, 100, 200, 500, 1000,2000,3000,4000, 50000, 100000],
        // processing:true,
        // serverSide:true,
        "oLanguage": {
            sLengthMenu: " Length of rows _MENU_ ",
        },

        ajax:{
            url:"{{ url('Main/fetch_brand') }}",
            dataType: "json",
            type:"POST",
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            // error:function()
            // {
            //     alert("Something went wrong. Please refresh the page.");
            //     location.reload();
            // }

        },

        order:[],

        buttons: [
            {
                extend:    'copyHtml5',
                text:      '<i class="fa fa-files-o"></i>',
                titleAttr: 'Copy',
                className: 'btn btn-outline-primary ',
                exportOptions: {
                    columns: "thead th:not(.noExport)"
                }

            },
            {
                extend:    'excelHtml5',
                text:      '<i class="fa fa-file-excel"></i>',
                titleAttr: 'Excel',
                className: 'btn btn-outline-primary ',
                exportOptions: {
                    columns: "thead th:not(.noExport)"
                }

            },

            {
                extend:    'csvHtml5',
                text:      '<i class="fa fa-file-csv"></i>',
                titleAttr: 'CSV',
                className: 'btn btn-outline-primary ',
                exportOptions: {
                    columns: "thead th:not(.noExport)"
                }


            },
            {
                extend:    'pdfHtml5',
                text:      '<i class="fa fa-file-pdf"></i>',
                titleAttr: 'PDF',
                className: 'btn btn-outline-primary ',
                exportOptions: {
                    columns: "thead th:not(.noExport)"
                }


            }
        ]
    } );
} );

</script>

contoller

    function brand(){
    if(session('role')){
    $obj = new  BackendModel;
    $data['data']=$obj->get_brand();

        return view('brand',$data);
    }else{
        return view('login');
    }
}
function fetch_brand(Request $request){

    $obj = new  BackendModel;
    $callData= $obj->call_brand();
    $totalData = count($obj->count_call_brand());
    $counter = 1;
    foreach ($callData as $row) {
        $callData = array();
        $callData[] = $counter;
        $callData[] = $row->name;
        $callData[] = '  <button type="button"  class="btn btn-sm btn-primary editfrom" data-id="{{ $row->id }}"  data-toggle="modal" data-target="#exampleModal1">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <span class="btn btn-sm  btn-danger"><i class="fas fa-trash"></i></span>';

        $data[] = $callData;
        $counter++;
    }
    $output = array(
        "draw"              =>  intval($request->input('draw')),
        "recordsTotal"      =>  intval($totalData),
        "recordsFiltered"   =>  intval($totalData),
        "data"              =>  $data
    );
    echo json_encode($output);


}

model

   public function call_brand(){
        $calling = 0;
        $query = $this->get_data_brand($calling);

        return $query;
    }
    public function count_call_brand(){
        $calling = 1;
        $query = $this->get_data_brand($calling);

        return $query;
    }
    public function get_data_brand($calling){

        if(!empty($_POST["order"]))
        {
            DB::orderBy($_POST['order']['0']['column'], $_POST['order']['0']['dir']);
        }


        if($calling==1){
            if(isset($_POST["length"]) && $_POST["length"]  != -1)
            {
               DB::limit($_POST['length'], $_POST['start']);
            }
        }
        if(isset($_POST["search"]["value"]))
        {
            $fields  = Schema::getColumnListing('brand');

            foreach ($fields as $field)
            {
                if($field!="id" ){
                    DB::where($field, 'like', '%'.$field.'%');


                }

            }
        }


        $query = DB::table('brand')->get();



        return $query;

    }