Laravel 5.8: красноречивая пагинация для Bootstrap Datatable
Я не мог найти ни одного такого вопроса. Все остальные вопросы не используют Bootstrap datatables, как я - они построили свою собственную таблицу.
Приложение My Laravel 5.8 возвращает текущий список пользователей в таблице datatable с возможностью поиска. Проблема в том, что он возвращает всех пользователей сразу, поэтому страница загружается очень медленно, так как приложение имеет много пользователей.
Мои routes\web.php
:
Route::get('/admin/customers', 'Admin\CustomerController@renderPage')->name('admin.customers');
My app\Http\Controllers\Admin\CustomerController.php
:
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use ConsoleTVs\Charts\Facades\Charts;
use App\User;
class CustomerController extends Controller
{
public function renderPage() {
$customers = User::get();
return view('pages.admin.customers')->with([
'customers' => $customers
]);
}
}
Моя таблица в представлении resources\views\pages\admin\customers.blade.php
генерируется следующим образом (я удалил не соответствующий HTML код):
<!-- Bootstrap -->
<link href="/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<!-- Datatables -->
<link rel="stylesheet" href="/css/dataTables.bootstrap.min.css">
<div class="table-responsive">
<table class="table table-condensed table-hover" id="customers-table">
<thead>
<tr>
<th>#</th>
<th>First name</th>
<th>Last Name</th>
<th>Email Address</th>
</tr>
</thead>
<tbody>
@foreach($customers as $customer)
<tr>
<td>{{ $customer->id }}</td>
<td>{{ $customer->first_name }}</td>
<td>{{ $customer->last_name }}</td>
<td>{{ $customer->email }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<!-- Datatables -->
<script src="/js/jquery.dataTables.min.js"></script>
<script src="/js/dataTables.bootstrap.min.js"></script>
<script>
// Datatable settings
$(document).ready(function() {
$('#customers-table').DataTable({
"language": {
"lengthMenu": "Show _MENU_ entires per page",
"search": "Search:",
"decimal": ".",
"thousands": ",",
"zeroRecords": "No entries found.",
"info": "Showing entries _START_ to _END_ of total _TOTAL_",
"infoEmpty": "No entries available.",
"infoFiltered": "(filtered from _MAX_ total entries)",
"paginate": {
"first": "First",
"last": "Last",
"next": "Next",
"previous": "Previous"
}
}
});
} );
</script>
Таким образом, возникает вопрос: Что мне нужно обновить, чтобы добавить поддержку разбиения на страницы?


Ответы - Laravel 5.8: красноречивая пагинация для Bootstrap Datatable / Laravel 5.8: Eloquent Pagination for Bootstrap Datatable

18.06.2019 10:37:58
Вместо рендеринга html на сервере, попробуйте загрузить DataTable через Ajax.
HTML
<table id="data-table" class="table table-striped table-bordered dt-responsive nowrap dataTable no-footer dtr-inline collapsed">
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
<th>E-Mail</th>
<th>Action</th>
</tr>
<tfoot></tfoot>
</table>
Яваскрипт
const table = $('#customer-table').DataTable({
'processing': true,
'serverSide': true,
'ajax': {
'url': 'customers/list',
'type': 'POST'
},
'columns': [
{'data': 'id'},
{'data': 'first_name'},
{'data': 'last_name'},
{'data': 'email'},
{
'orderable': false,
'searchable': false,
'data': null,
'render': function (data, type, row, meta) {
// render custom html
return '<button type="button" class="btn btn-info">Edit</button>';
}
}
],
});
РНР
На стороне сервера возьмите параметры POST-запроса и постройте динамический запрос (с помощью QueryBuilder).
Затем сопоставить результат в DataTable совместимы ответа JSON :
Действие контроллера
// Build dynamic query
// ...
// Fetch result set
// ...
return response()->json([
'recordsTotal' => $count,
'recordsFiltered' => $count,
'draw' => $draw,
'data' => $rows,
];
Дополнительные сведения об ответе json: обработка данных на стороне сервера

if
-условия в таблице для отображения различных значков для булевых символов, например, или конвертировать метки времени даты с помощью Carbon
? Потому что, насколько я понял, <tbody></tbody>
быть пустым, верно?



17.01.2020 03:12:03
public function renderPage() {
$customers = DB::table('users')->paginate(15);
return view('pages.admin.customers')->with([
'customers' => $customers
]);
}
