Laravel Manual Pagination: Complete Guide
In Laravel, you can manually implement pagination using the Paginator class. Firstly, data needs to be queried through the Eloquent model and then use the Paginator class to paginate the query results.
Here is an example code:
use App\Models\User;
use Illuminate\Pagination\Paginator;
// 查询数据
$users = User::all();
// 每页显示的数量
$perPage = 10;
// 当前页码
$page = request()->get('page', 1);
// 创建一个Paginator实例
$paginator = new Paginator($users->forPage($page, $perPage), $users->count(), $perPage, $page, [
'path' => Paginator::resolveCurrentPath(),
]);
// 获取分页数据
$paginatedUsers = $paginator->items();
// 返回分页数据
return view('users.index', ['users' => $paginatedUsers, 'paginator' => $paginator]);
In the view file, you can utilize the $paginator object to create pagination links.
@foreach ($users as $user)
<!-- 显示用户信息 -->
@endforeach
{{ $paginator->links() }}
By using the above code, you can manually implement pagination and display pagination links in the view.