
Laravel Resources 提供了一种将 Eloquent 模型或集合转换为 JSON 的强大且灵活的方式。当涉及到集合数据的分页时,Laravel 提供了一个专门的 ResourceCollection 类,它能够自动处理来自 paginate() 方法的分页器实例,并将其转换为包含 data、links 和 meta 键的标准 JSON 结构。
ResourceCollection 的设计目的是作为 API 响应的顶层资源,用于呈现一个已分页的资源集合。它期望在构造函数中接收一个分页器实例(例如 LengthAwarePaginator 或 Paginator),而不是一个普通的集合或分页器内部的 collection 属性。
为了在 API 响应中正确地显示分页链接和元数据,最推荐的做法是在控制器或路由中执行分页操作,然后将分页结果直接传递给你的 ResourceCollection。
首先,为集合中的每个单独项定义一个资源类。例如,如果你有一个 Item 模型,可以创建一个 ItemResource:
// app/Http/Resources/ItemResource.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class ItemResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
"id" => $this->id,
"name" => $this->name,
"slug" => $this->slug,
"image" => imageGenerate("items", $this->image), // 假设 imageGenerate 是一个辅助函数
"code" => $this->code,
"category" => $this->category->name ?? "", // 假设有 category 关系
];
}
}接下来,创建一个 ResourceCollection 类来封装 ItemResource 的集合。这个类通常只需要指定它所使用的单个资源类:
// app/Http/Resources/ItemCollection.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class ItemCollection extends ResourceCollection
{
/**
* The resource that this collection of resources is wrapping.
*
* @var string
*/
public $collects = ItemResource::class;
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
// 默认情况下,ResourceCollection 会自动处理分页元数据。
// 如果需要添加额外的元数据,可以在这里返回一个包含 'data' 和其他键的数组。
return parent::toArray($request);
}
}最后,在你的控制器方法或路由闭包中,执行 Eloquent 查询并调用 paginate() 方法,然后将返回的分页器实例传递给 ItemCollection:
// app/Http/Controllers/ItemController.php
namespace App\Http\Controllers;
use App\Models\Item;
use App\Http\Resources\ItemCollection;
use Illuminate\Http\Request;
class ItemController extends Controller
{
public function index()
{
// 获取所有 Item 并分页,每页20条
$items = Item::paginate(20);
// 将分页结果传递给 ItemCollection
return new ItemCollection($items);
}
}或者直接在路由中:
// routes/api.php 或 routes/web.php
use App\Models\Item;
use App\Http\Resources\ItemCollection;
Route::get('/items', function () {
return new ItemCollection(Item::paginate(20));
});当上述代码执行时,API 响应将自动包含 data 数组(包含 ItemResource 转换后的数据)、links 对象(包含分页链接,如 first, last, prev, next 等)和 meta 对象(包含分页元数据,如 current_page, from, last_page, per_page, to, total 等)。
示例 JSON 响应结构:
{
"data": [
{
"id": 1,
"name": "Item A",
"slug": "item-a",
"image": "http://example.com/images/item-a.jpg",
"code": "CODE001",
"category": "Category One"
},
{
"id": 2,
"name": "Item B",
"slug": "item-b",
"image": "http://example.com/images/item-b.jpg",
"code": "CODE002",
"category": "Category One"
}
// ...更多 Item 数据
],
"links": {
"first": "http://example.com/api/items?page=1",
"last": "http://example.com/api/items?page=5",
"prev": null,
"next": "http://example.com/api/items?page=2"
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 5,
"path": "http://example.com/api/items",
"per_page": 20,
"to": 20,
"total": 100
}
}用户最初的问题中提到了在父资源(如 SectionResource)内部嵌套一个分页的 ItemCollection:
// SectionResource 内部的 toArray 方法
public function toArray($request)
{
return [
// ... 其他字段
"items" => new ItemCollection($this->items()->paginate(20)),
];
}这种做法虽然技术上可行,但通常不推荐用于生成顶层 API 分页链接。原因如下:
如果你的业务逻辑确实需要在一个父资源内部展示一个分页的子集合,并且接受分页信息嵌套,那么上述代码是有效的。但如果目标是让 items 集合的分页链接成为 API 响应的根级别,那么应该为 items 创建一个单独的 API 端点,并直接返回 ItemCollection(Item::paginate())。
在 Laravel Resource 中显示分页链接的关键在于正确使用 ResourceCollection。通过在控制器或路由中执行数据分页,并将返回的分页器实例直接传递给 ResourceCollection,你可以轻松地构建符合 RESTful 规范且包含完整分页元数据的 API 响应。理解 ResourceCollection 的设计意图,并遵循将分页逻辑放在控制器/路由层的最佳实践,将有助于构建清晰、可维护的 API。
以上就是在 Laravel Resource 中优雅地显示分页链接的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号