Я новичок в Laravel PHP Framework
и в настоящее время продолжаю проект, который был оставлен кем-то.поэтому я пытаюсь повторить его код , чтобы создать новый список данных, используя DataTables library
То, чего я хочу достичь - это простая вещь, просто показать список данных .он использует новую таблицу.Я пойду заранее, чтобы создать другую функцию, такую как edit
, details
, action
и т. Д., Но в настоящее время просто показать, что список данных все еще не работает.
Ошибка:
Предупреждение DataTables: идентификатор таблицы = таблица - ошибка Ajax.Для получения дополнительной информации об этой ошибке см. http://datatables.net/tn/7
Эта ошибка появляется всякий раз, когда я пытаюсь получить данные.
Использование инструментов разработчика Chrome не очень помогает, я не получил подробностей, что не так:
Инструменты разработчика Chrome, вкладка "Сеть":
Таблицы:
** Код вида: **
@extends('layouts.admin.main')
@section('pageTitle', 'Sodaqoh Revenue')
@push('head')
<!-- DataTables -->
<link href="{{ asset('plugins/datatables/dataTables.bootstrap4.min.css') }}" rel="stylesheet" type="text/css">
<link href="{{ asset('plugins/datatables/buttons.bootstrap4.min.css') }}" rel="stylesheet" type="text/css">
<!-- Responsive datatable examples -->
<link href="{{ asset('plugins/datatables/responsive.bootstrap4.min.css') }}" rel="stylesheet" type="text/css">
@endpush
@section('content')
<div class="row">
<div class="col-12">
<div class="card m-b-20">
<div class="card-body">
<table id="table" class="table table-striped table-bordered dt-responsive nowrap" style="border-collapse: collapse; border-spacing: 0; width: 100%;">
<thead>
<tr>
<th width="5">#</th>
<th>{{ __('Name') }}</th>
<th>{{ __('Month') }}</th>
<th>{{ __('Year') }}</th>
<th>{{ __('Total') }}</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<!-- end col -->
</div>
@endsection
@push('scripts')
<script src="{{ asset('plugins/jquery-sparkline/jquery.sparkline.min.js') }}"></script>
<script src="{{ asset('plugins/jquery-sparkline/jquery.sparkline.min.js') }}"></script>
<!-- Required datatable js -->
<script src="{{ asset('plugins/datatables/jquery.dataTables.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/dataTables.bootstrap4.min.js') }}"></script>
<!-- Buttons examples -->
<script src="{{ asset('plugins/datatables/dataTables.buttons.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/buttons.bootstrap4.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/jszip.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/pdfmake.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/vfs_fonts.js') }}"></script>
<script src="{{ asset('plugins/datatables/buttons.html5.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/buttons.print.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/buttons.colVis.min.js') }}"></script>
<!-- Responsive examples -->
<script src="{{ asset('plugins/datatables/dataTables.responsive.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/responsive.bootstrap4.min.js') }}"></script>
<script>
var oTable;
oTable = $('#table').DataTable({
processing: true,
serverSide: true,
dom: 'lBfrtip',
order: [[ 3, "asc" ]],
pagingType: 'full_numbers',
buttons: [
{
extend: 'print',
autoPrint: true,
customize: function ( win ) {
$(win.document.body)
.css( 'padding', '2px' )
.prepend(
'<img src="{{ asset('assets/images/logo.png') }}" style="float:right; top:0; left:0;height: 40px;right: 10px;background: #101010;padding: 8px;border-radius: 4px" /><h5 style="font-size: 9px;margin-top: 0px;"><br/><font style="font-size:14px;margin-top: 5px;margin-bottom:20px;"> @yield('pageTitle')</font><br/><br/><font style="font-size:8px;margin-top:15px;">{{date('Y-m-d h:i:s')}}</font></h5><br/><br/>'
);
$(win.document.body).find( 'div' )
.css( {'padding': '2px', 'text-align': 'center', 'margin-top': '-50px'} )
.prepend(
''
);
$(win.document.body).find( 'table' )
.addClass( 'compact' )
.css( { 'font-size': '9px', 'padding': '2px' } );
},
title: '',
orientation: 'landscape',
exportOptions: {columns: ':visible'} ,
text: '<i class="fa fa-print" data-toggle="tooltip" title="" data-original-title="Print"></i>',
//className: 'btn btn-primary'
},
{extend: 'colvis', text: '<i class="fa fa-eye" data-toggle="tooltip" title="" data-original-title="Column visible"></i>'},
{extend: 'csv', text: '<i class="fa fa-file-excel" data-toggle="tooltip" title="" data-original-title="Export CSV"></i>'}
],
//sDom: "<'table-responsive fixed't><'row'<p i>> B",
sPaginationType: "bootstrap",
destroy: true,
responsive: true,
scrollCollapse: true,
oLanguage: {
"sLengthMenu": "_MENU_ ",
"sInfo": "Showing <b>_START_ to _END_</b> of _TOTAL_ entries"
},
lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
ajax: {
url: '{!! route('sodaqoh-revenue.list-index') !!}',
data: function (d) {
d.range = $('input[name=drange]').val();
}
},
columns: [
// { data: "rownum", name: "rownum" },
{ data: "name", name: "name" },
{ data: "month", name: "month" },
{ data: "year", name: "year" },
{ data: "total", name: "total" }
],
}).on( 'processing.dt', function ( e, settings, processing ) {});
$("#table_wrapper .dt-buttons").appendTo("#table_wrapper .dataTables_length");
$('#formsearch').submit(function () {
oTable.search( $('#search-table').val() ).draw();
return false;
} );
oTable.page.len(25).draw();
function modalDelete(id) {
swal({
title: "Are you sure?",
text: "Delete this record",
type: "warning",
showCancelButton: !0,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel!",
confirmButtonClass: "btn btn-success",
cancelButtonClass: "btn btn-danger m-l-10",
buttonsStyling: !1
}).then(function() {
deleteRecord(id);
}, function(t) {
"cancel" === t && swal("Cancelled", "Your data is safe :)", "error")
})
}
function deleteRecord(id){
$.ajax({
url: '{{route("sodaqoh-revenue.index")}}' + "/" + id + '?' + $.param({"_token" : '{{ csrf_token() }}' }),
type: 'DELETE',
complete: function(data) {
oTable.draw();
swal("Deleted!", "Data is successfully deleted", "success");
}
});
}
</script>
@endpush
Контроллер:
<?php
namespace App\Http\Controllers\Admin;
use App\DzikirPlaylistCategory;
use App\DzikirPlaylist;
use App\Http\Controllers\Controller;
use App\SodaqohRevenue;
use App\User;
use DB;
use Illuminate\Http\Request;
use Session;
class SodaqohRevenueController extends Controller
{
protected $rules = [
'id' => 'required',
'name' => 'required',
'month' => 'required',
'year' => 'required',
'total' => 'required',
'point_total' => 'required',
'point_rate' => 'required',
];
public function index()
{
return view('admin.sodaqoh-revenue.index');
}
public function listIndex(Request $request)
{
DB::statement(DB::raw('set @rownum=0'));
$model = SodaqohRevenue::all();
$datatables = app('datatables')->of($model);
// ->editColumn('status', function ($model) {
// return $model->getStatusLabel();
// })
// ->addColumn('point', function ($model) {
// return $model->userDetail ? $model->userDetail->point : 0;
// })
// ->addColumn('action', function ($model) {
// return "<a href='". route('user-apps.show', ['id' => $model->id]) ."' class='btn btn-primary btn-sm'><i class='fa fa-eye'></i></a>";
// });
return $datatables->make(true);
}
}
Модель:
<?php
namespace App;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
class SodaqohRevenue extends BaseModel
{
use SoftDeletes;
const ROLE_APPS = 1;
const ROLE_SUPERADMIN = 10;
const STATUS_ACTIVE = 1;
const STATUS_NEED_CONFIRMATION = 5;
const STATUS_BLOCKED = 0;
const REGISTER_TYPE_GENERAL = 1;
const REGISTER_TYPE_GOOGLE = 2;
const REGISTER_TYPE_FACEBOOK = 3;
use Notifiable;
protected $table = 'revenue';
protected $fillable = [
'id',
'name',
'month',
'year',
'total',
'point_total',
'point_rate',
];
protected $hidden = [
'created_by',
'updated_by'
];
public function __construct(array $attributes = array())
{
parent::__construct($attributes);
}
public function scopeRoleMobileApp($query)
{
return $query->where($this->table . '.role', self::ROLE_APPS);
}
}
Веб-маршрут:
...
Route::get('/sodaqoh-revenue/list-index', ['as' => 'sodaqoh-revenue.list-index', 'uses' => 'Admin\\SodaqohRevenueController@listIndex']);
Route::resource('/sodaqoh-revenue', 'Admin\\SodaqohRevenueController');
...
Журнал Laravel:
[2019-07-04 21:35:56] local.ERROR: Невозможно использовать Illuminate \ Notifications \ Notifiable в качестве уведомляемого, поскольку имя уже используется {"userId": 1, "email": "info.zipedia@gmail.com", "исключение": "[объект] (Symfony \ Component \ Debug \ Exception \ FatalErrorException (код: 64): невозможно использовать Illuminate \ Notifications \ Notifiable в качестве уведомляемого, поскольку имя уже находится виспользуйте по адресу /Users/zulkifli/zipediaPrj/webZipedia-zul-dev@github/app/SodaqohRevenue.php:7) [stacktrace] #0 {main} "}
Есть идеи, что случилось?любая помощь приветствуется.