简体   繁体   English

Laravel 5.8:Bootstrap 数据表的雄辩分页

[英]Laravel 5.8: Eloquent Pagination for Bootstrap Datatable

I couldn't find any questions like this.我找不到任何这样的问题。 All other questions are not using the Bootstrap datatables like me - they built their own table.所有其他问题都没有像我一样使用 Bootstrap 数据表 - 他们构建了自己的表。

My Laravel 5.8 application returns currently a list of users in a searchable datatable.我的 Laravel 5.8 应用程序当前返回可搜索数据表中的用户列表。 The problem is, that it's returning ALL users at once, so the page loads really slow since the application has a lot of users.问题是,它一次返回所有用户,因此页面加载速度非常慢,因为应用程序有很多用户。

My routes\\web.php :我的routes\\web.php

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

My app\\Http\\Controllers\\Admin\\CustomerController.php :我的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
            ]);
    }
}

My table in the view resources\\views\\pages\\admin\\customers.blade.php gets generated like this (I've removed the not relevant HTML code):我在视图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>

So the question is: What do I need to update to what in order to add support for pagination?所以问题是:为了添加对分页的支持,我需要更新什么?

Instead of rendering the html on the server, try to load the DataTable via Ajax.尝试通过 Ajax 加载 DataTable,而不是在服务器上呈现 html。

HTML 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 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 PHP

On the server-side take the POST request parameters and build a dynamic query (with the QueryBuilder).在服务器端获取 POST 请求参数并构建一个动态查询(使用 QueryBuilder)。

Then map the result set into a DataTable compatible JSON response:然后将结果集映射到 DataTable 兼容的 JSON 响应中:

The controller action控制器动作


// Build dynamic query
// ...

// Fetch result set
// ...

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

More details about the json response: DataTable Server-side processing有关 json 响应的更多详细信息: DataTable 服务器端处理

public function renderPage() {
    $customers = DB::table('users')->paginate(15);

    return view('pages.admin.customers')->with([
            'customers' => $customers
        ]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM