温馨提示×

centos laravel如何实现分页

小樊
52
2025-09-15 17:50:59
栏目: 智能运维

在 Laravel 中,实现分页非常简单。这里是一个基本的示例,展示了如何在 CentOS 系统上使用 Laravel 实现分页。

  1. 首先,确保你已经安装了 Laravel。如果还没有安装,可以通过以下命令安装:
composer create-project --prefer-dist laravel/laravel your_project_name

your_project_name 替换为你的项目名称。

  1. 接下来,创建一个新的控制器。在终端中运行以下命令:
php artisan make:controller YourController

YourController 替换为你的控制器名称。

  1. 在新创建的控制器中,添加一个方法来获取数据并实现分页。例如:
<?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 替换为你的视图文件名称。

  1. 在视图文件中(例如 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>
  1. 最后,确保你的路由配置正确。在 routes/web.php 文件中添加以下路由:
use App\Http\Controllers\YourController;

Route::get('/your-route', [YourController::class, 'index']);

/your-route 替换为你想要访问的 URL 路径。

现在,当你访问 /your-route 时,你应该能看到分页的数据。点击分页链接,你可以浏览不同页面的数据。

0