php - 分页输出 laravel blade

标签 php laravel pagination

我是 Laravel 的初学者。

我需要用数据对我的表格进行分页。无法理解如何设置链接。我正在尝试搜索一些文档,但不明白我该怎么做。

我的 Controller :

public function index()
    {
        $users = Viewers::all()->forPage(1, 5)->sortByDesc('last_activity');
        $users->setPath('/admin');
        return view('pages.admin.dashboard', ['users'=>$users]);
    }

我的dashboard.blade.php:

@extends('layouts.admin')

@section('content')
    <div class="content">
        <table class="table">
            <thead>
            <tr>
                <th class="text-center">#</th>
                <th>IP</th>
                <th>Request URI</th>
                <th>Country</th>
                <th>City</th>
                <th>Device</th>
                <th>Last Activity</th>
            </tr>
            </thead>
            @foreach($users as $user)
                <tbody>

                <tr>
                    <td class="text-center">{{$user->id}}</td>
                    <td>{{$user->ip_address}}</td>
                    <td>{{$user->request_uri}}</td>
                    <td>{{$user->country}}</td>
                    <td>{{$user->city}}</td>
                    <td>{{$user->device}}</td>
                    <td>{{$user->last_activity}}</td>
                </tr>
                </tbody>
            @endforeach
        </table>
        <nav aria-label="Page navigation example">
            <ul class="pagination">
                <li class="page-item"><a class="page-link" href="#">Previous</a></li>
                <li class="page-item"><a class="page-link" href="#">1</a></li>
                <li class="page-item"><a class="page-link" href="#">2</a></li>
                <li class="page-item"><a class="page-link" href="#">3</a></li>
                <li class="page-item"><a class="page-link" href="#">Next</a></li>
            </ul>
        </nav>
    </div>
@endsection

最佳答案

Viewers::all() 将数据库中的每条记录加载到 Collection 中。集合有 sortBy()sortByDesc() 方法,但是在查询时作为 Builder 实例的模型有一个 orderBy() 方法。在大多数情况下,使用 DB 排序比 PHP/Laravel 排序更有效,因此除非需要,否则尽量不要使用 ::all()

话虽如此,您的查询可以固定为:

$users = Viewers::orderBy('last_activity', 'DESC')->paginate(100); // Replace 100 with desired number per page

然后,在您的 .blade.php 文件中,使用 Pagination 实例上可用的 links() 方法:

{{ $users->links() }}

这将根据每页的记录数输出 First、Previous、Page(s)、Next 和 Last 链接。

关于php - 分页输出 laravel blade,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65024806/

相关文章:

php - jQuery AJAX 调用 - 是否可以取消不需要的调用?

php - Laravel 5 文件夹结构中的文件保存位置?

php - 从 Paypal IPN 检查金额

php - (1/1) FatalErrorException 在 ClearanceMiddleware.php 第 17 行中调用 null 的成员函数 hasPermissionTo()

函数中的 php 分页

php - 获取一年中每个月的总计,包括没有结果的月份

php - 如何使用 Laravel 的 block 来避免内存不足?

php - Laravel - 如何在 $query 函数中定义变量?

javascript - 使用 React Komposer 进行分页

CakePHP:使用自定义数组提供 paginate()