Laravel 5.8: красноречивая нумерация страниц для Bootstrap Datatable - PullRequest
0 голосов
/ 18 июня 2019

Я не мог найти такие вопросы, как этот.Все остальные вопросы не используют таблицы данных Bootstrap, как я, - они создали свою собственную таблицу.

Приложение Laravel 5.8 в настоящее время возвращает список пользователей в доступной для поиска базе данных.Проблема в том, что он возвращает ВСЕХ пользователей одновременно, поэтому страница загружается очень медленно, так как в приложении много пользователей.

Мой routes\web.php:

Route::get('/admin/customers', 'Admin\CustomerController@renderPage')->name('admin.customers');

Мой 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>

Итак, вопрос в том, чтомне нужно обновить до чего, чтобы добавить поддержку пагинации?

1 Ответ

1 голос
/ 18 июня 2019

Вместо того, чтобы рендерить 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>

JavaScript

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>';
            }
        }
    ],
});

PHP

На стороне сервера возьмите параметры запроса POST и создайте динамический запрос (с помощью QueryBuilder).

Затем сопоставьтенабор результатов в ответ JSON, совместимый с DataTable:

Действие контроллера


// Build dynamic query
// ...

// Fetch result set
// ...

return response()->json([
    'recordsTotal' => $count,
    'recordsFiltered' => $count,
    'draw' => $draw,
    'data' => $rows,
];

Подробнее об ответе json: Обработка данных на стороне сервера

...