php - 分页输出 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
解决方案
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 链接。
推荐阅读
- ruby - 如何在保留原始上下文的同时将产量与重试循环结合起来?
- python - 如何使用移位在时间戳两行之间进行减法 - Pandas Python
- c++ - 作为一般经验法则,我应该更喜欢直接列表初始化而不是复制初始化吗?
- python - 基于硒日期的刮表
- java - 如何使用 Apache-POI 为幻灯片中的链接视频创建 pptx 文件
- git - 当我选中“阻止命令行推送”复选框时,为什么我不能推送?
- azure - 将域的子文件夹映射到 azure app servive
- javascript - 如何使用 lodash 在 javascript 中实现多级排序?
- android - 如何在加载应用程序时存储未来数据以供进一步使用?# 颤动
- assembly - 如何堆叠(推送)xPSR?