在 Laravel 中,实现分页非常简单。这里是一个基本的示例,展示了如何在 CentOS 系统上使用 Laravel 实现分页。
composer create-project --prefer-dist laravel/laravel your_project_name
将 your_project_name 替换为你的项目名称。
php artisan make:controller YourController
将 YourController 替换为你的控制器名称。
<?php
namespace App\Http\Controllers;
use App\Models\YourModel;
use Illuminate\Http\Request;
class YourController extends Controller
{
public function index(Request $request)
{
// 获取数据并实现分页,每页显示 10 条记录
$data = YourModel::paginate(10);
// 将数据传递给视图
return view('your_view', compact('data'));
}
}
将 YourModel 替换为你的数据模型名称,将 your_view 替换为你的视图文件名称。
resources/views/your_view.blade.php),你可以使用以下代码来显示分页链接:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>分页示例</title>
</head>
<body>
<table>
<thead>
<tr>
<th>ID</th>
<th>名称</th>
<!-- 其他列 -->
</tr>
</thead>
<tbody>
@foreach ($data as $item)
<tr>
<td>{{ $item->id }}</td>
<td>{{ $item->name }}</td>
<!-- 其他列 -->
</tr>
@endforeach
</tbody>
</table>
{{-- 显示分页链接 --}}
{{ $data->links() }}
</body>
</html>
routes/web.php 文件中添加以下路由:use App\Http\Controllers\YourController;
Route::get('/your-route', [YourController::class, 'index']);
将 /your-route 替换为你想要访问的 URL 路径。
现在,当你访问 /your-route 时,你应该能看到分页的数据。点击分页链接,你可以浏览不同页面的数据。