在此示例中,将开始向您说明如何使用laravel分页。
步骤1:添加路由
首先,我们为具有分页函数的列表用户设置路由。
routes/web.php
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\UserController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('users', [UserController::class, 'index']);
步骤2:创建控制器
与上述路由相同,这里我们将为路由添加一种新方法。 index()将返回带有分页数据,因此让我们添加以下内容:
app/Http/Controllers/UserController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $data = User::paginate(5); return view('users',compact('data')); } }
步骤3:创建视图
在此步骤中,您需要创建用户视图blade文件,并将与links()一起使用,以便它将自动生成分页。
resources/views/users.blade.php
<!DOCTYPE html> <html> <head> <title>Laravel 8 CRUD Application - 无涯教程</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet"> </head> <body> <div class="container"> <h1>Laravel 8 Pagination Example - 无涯教程</h1> <table class="table table-bordered"> <thead> <tr> <th>Name</th> <th width="300px;">Action</th> </tr> </thead> <tbody> @if(!empty($data) && $data->count()) @foreach($data as $key => $value) <tr> <td>{{ $value->name }}</td> <td> <button class="btn btn-danger">Delete</button> </td> </tr> @endforeach @else <tr> <td colspan="10">There are no data.</td> </tr> @endif </tbody> </table> {!! $data->links() !!} </div> </body> </html>
现在您可以运行并检查此示例。这是一个非常简单和基本的例子。
如果使用bootstrap程序,则必须在服务提供者(service provider)上添加useBootstrap(),如下所示:
app\Providers\AppServiceProvider.php
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Pagination\Paginator; class AppServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ public function register() { } /** * Bootstrap any application services. * * @return void */ public function boot() { Paginator::useBootstrap(); } }
如果您需要预先使用分页,则可以在下面看到如何使用。
Pagination与appends parameter
{!! $data->appends(['sort' => 'votes'])->links() !!}
与追加分页请求所有参数
{!! $data->appends(Request::all())->links() !!}