【发布时间】:2020-11-27 22:40:40
【问题描述】:
我是 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
【问题讨论】:
-
请查看分页文档:laravel.com/docs/8.x/pagination。在您看来,这应该像
$users = Users::orderBy('last_activity', 'DESC')->paginate(100);一样简单,然后是$users->links()。旁注,不要使用User::all(),除非你想要所有用户。与数据库排序相比,将它们加载到内存中进行排序是低效的。 -
将此行更改为
$users = Viewers::sortByDesc('last_activity')->paginate(10);现在只需将此代码{{ $users->links() }}放在foreach 循环下 -
@sta
'Call to undefined method App/Viewers::sortByDesc()'。你误会了Builder和Collection方法。模型查询,在通过闭包之前是Builder实例,没有sortBy()或sortByDesc(),需要使用orderBy()。Collections 使用sortBy()。请查看并更正您的评论。 laravel.com/api/8.x/Illuminate/Database/Query/…、laravel.com/api/8.x/Illuminate/Support/… 和 laravel.com/api/8.x/Illuminate/Support/…。 -
@Tim Lewis 我的愚蠢错误
-
@TimLewis 添加答案 - 我会接受的
标签: php laravel pagination