search
HomeBackend DevelopmentPHP Tutorial[ Laravel 5.2 文档 ] 服务 -- 分页

1、简介

在其他框架中,分页是件非常痛苦的事,Laravel则使其变得轻而易举。Laravel能够基于当前页智能生成一定范围的链接,且生成的HTML兼容 Bootstrap CSS 框架。

2、基本使用

2.1 基于查询构建器分页

有多种方式实现分页,最简单的方式就是使用查询构建器或 Eloquent模型的 paginate方法。该方法基于当前用户查看页自动设置合适的偏移(offset)和限制(limit)。默认情况下,当前页通过HTTP请求查询字符串参数 ?page的值判断。当然,该值由Laravel自动检测,然后自动插入分页器生成的链接中。

让我们先来看看如何在查询上调用 paginate方法。在本例中,传递给 paginate的唯一参数就是你每页想要显示的数目,这里我们指定每页显示 15个:

<?phpnamespace App\Http\Controllers;use DB;use App\Http\Controllers\Controller;class UserController extends Controller{    /**     * 显示应用中的所有用户     *     * @return Response     */    public function index()    {        $users = DB::table('users')->paginate(15);        return view('user.index', ['users' => $users]);    }}

注意:目前,使用 groupBy的分页操作不能被Laravel有效执行,如果你需要在分页结果中使用 groupBy,推荐你手动查询数据库然后创建分页器。

简单分页

如果你只需要在分页视图中简单的显示“下一个”和“上一个”链接,可以使用 simplePaginate方法来执行该查询。在渲染包含大数据集的视图且不需要显示每个页码时非常有用:

$users = DB::table('users')->simplePaginate(15);

2.2 基于Eloquent 模型分页

你还可以对Eloquent查询结果进行分页,在本例中,我们对 User模型进行分页,每页显示 15条记录。正如你所看到的,该语法和基于查询构建器的分页差不多:

$users = App\User::paginate(15);

当然,你可以在设置其它约束调价之后调用 paginate,比如 where子句:

$users = User::where('votes', '>', 100)->paginate(15);

你也可以使用 simplePaginate方法:

$users = User::where('votes', '>', 100)->simplePaginate(15);

2.3 手动创建分页器

有时候你可能想要通过传递数组数据来手动创建分页实例,你可以基于自己的需求通过创建 Illuminate\Pagination\Paginator或 Illuminate\Pagination\LengthAwarePaginator实例来实现。

Paginator类不需要知道结果集中数据项的总数;然而,正因如此,该类也没有提供获取最后一页索引的方法。

LengthAwarePaginator接收参数和 Paginator几乎一样,只是,它要求传入结果集的总数。

换句话说, Paginator对应 simplePaginate方法,而 LengthAwarePaginator对应 paginate方法。

当手动创建分页器实例的时候,应该手动对传递到分页器的结果集进行“切片”,如果你不确定怎么做,查看PHP函数 array_slice。

3、在视图中显示分页结果

当你调用查询构建器或Eloquent查询上的 paginate或 simplePaginate方法时,你将会获取一个分页器实例。当调用 paginate方法时,你将获取 Illuminate\Pagination\LengthAwarePaginator,而调用方法 simplePaginate时,将会获取 Illuminate\Pagination\Paginator实例。这些对象提供相关方法描述这些结果集,除了这些帮助函数外,分页器实例本身就是迭代器,可以像数组一样对其进行循环调用。

所以,获取到结果后,可以按如下方式使用Blade显示这些结果并渲染页面链接:

<div class="container">    @foreach ($users as $user)        {{ $user->name }}    @endforeach</div>{!! $users->links() !!}

links方法将会将结果集中的其它页面链接渲染出来。每个链接已经包含了 ?page查询字符串变量。记住, render方法生成的HTML兼容 Bootstrap CSS 框架。

注意:我们从Blade模板调用 render方法时,确保使用 {!! !!}语法以便HTML链接不被过滤。

自定义分页链接

setPath方法允许你生成分页链接时自定义分页器使用的URI,例如,如果你想要分页器生成形如 http://example.com/custom/url?page=N的链接,应该传递 custom/url到 setPath方法:

Route::get('users', function () {    $users = App\User::paginate(15);    $users->setPath('custom/url');    //});

添加参数到分页链接

你可以使用 appends方法添加查询参数到分页链接查询字符串。例如,要添加 &sort=votes到每个分页链接,应该像如下方式调用 appends:

{!! $users->appends(['sort' => 'votes'])->links() !!}

如果你想要添加”哈希片段”到分页链接,可以使用 fragment方法。例如,要添加 #foo到每个分页链接的末尾,像这样调用 fragment方法:

{!! $users->fragment('foo')->links() !!}

更多辅助方法

你还可以通过如下分页器实例上的方法访问更多分页信息:

  • $results->count()
  • $results->currentPage()
  • $results->firstItem()
  • $results->hasMorePages()
  • $results->lastItem()
  • $results->lastPage() (使用simplePaginate时无效)
  • $results->nextPageUrl()
  • $results->perPage()
  • $results->previousPageUrl()
  • $results->total() (使用simplePaginate时无效)
  • $results->url($page)

4、将结果转化为JSON

Laravel分页器结果类实现了 Illuminate\Contracts\Support\JsonableInterface契约并实现 toJson方法,所以将分页结果转化为JSON非常简单。

你还可以简单通过从路由或控制器动作返回分页器实例将转其化为JSON:

Route::get('users', function () {    return App\User::paginate();});

从分页器转化来的JSON包含了元信息如 total,  current_page, last_page等等,实际的结果对象数据可以通过该JSON数组中的 data键访问。下面是一个通过从路由返回的分页器实例创建的JSON例子:

{   "total": 50,   "per_page": 15,   "current_page": 1,   "last_page": 4,   "next_page_url": "http://laravel.app?page=2",   "prev_page_url": null,   "from": 1,   "to": 15,   "data":[        {            // Result Object        },        {            // Result Object        }   ]}
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.