首页 > 解决方案 > 分页输出 laravel 刀片

问题描述

我是 Laravel 的初学者。

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

我的控制器:

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

标签: phplaravelpagination

解决方案


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文件中,使用links()Pagination 实例上可用的方法:

{{ $users->links() }}

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


推荐阅读