简介
在构建 API 时,你可能需要一个转换层,该层介于你的 Eloquent 模型与实际返回给应用用户的 JSON 响应之间。例如,你可能希望向一部分用户显示某些属性,而对其他用户则不显示;又或者你可能希望在模型的 JSON 表示中始终包含某些关联关系。Eloquent 的资源类能让你以直观且便捷的方式,将模型和模型集合转换为 JSON。
当然,你始终可以通过模型或集合的 toJson 方法将其转换为 JSON;不过,Eloquent 资源可针对模型及其关联关系的 JSON 序列化,提供更精细、更稳健的控制。
生成资源
要生成资源类,你可以使用 make:resource Artisan 命令。默认情况下,资源会被放置在应用的 app/Http/Resources 目录中。资源类继承自 Illuminate\Http\Resources\Json\JsonResource 类:
php artisan make:resource UserResource资源集合
除了生成转换单个模型的资源,你还可以生成负责转换模型集合的资源。这样,你的 JSON 响应中便能包含与特定资源整个集合相关的链接及其他元信息。
若要创建资源集合,在创建资源时应使用 --collection 标志。或者,在资源名称中加入 Collection 一词,Laravel 便会据此创建集合资源。集合资源类继承自 Illuminate\Http\Resources\Json\ResourceCollection 类:
php artisan make:resource User --collection
php artisan make:resource UserCollection概念概览
这是对资源和资源集合的高层级概览。强烈建议你阅读本文档的其他章节,以便更深入地了解资源为你提供的自定义功能与强大能力。
在深入探究编写资源时可用的全部选项前,我们先从高层级了解一下资源在 Laravel 中是如何使用的。资源类代表需要转换为 JSON 结构的单个模型。例如,下面是一个简易的 UserResource 资源类:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
/**
* 将资源转换为数组。
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}每个资源类都会定义一个 toArray 方法,该方法返回一个属性数组;当资源作为路由或控制器方法的响应返回时,该数组将被转换为 JSON。
请注意,我们可以直接通过 $this 变量访问模型属性。这是因为资源类会自动将属性和方法的访问代理到底层模型,从而便于访问。资源定义完成后,便可以在路由或控制器中返回。资源通过其构造函数接收底层模型实例:
use App\Http\Resources\UserResource;
use App\Models\User;
Route::get('/user/{id}', function (string $id) {
return new UserResource(User::findOrFail($id));
});为方便起见,你可以使用模型的 toResource 方法,该方法会依据框架约定,自动发现模型对应的资源:
return User::findOrFail($id)->toResource();调用 toResource 方法时,Laravel 会尝试在最接近模型命名空间的 Http\Resources 命名空间中,查找与模型名称匹配、且可选以 Resource 为后缀的资源。
如果你的资源类未遵循此命名约定,或位于不同的命名空间,你可以使用 UseResource 特性为模型指定默认资源:
<?php
namespace App\Models;
use App\Http\Resources\CustomUserResource;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Attributes\UseResource;
#[UseResource(CustomUserResource::class)]
class User extends Model
{
// ...
}或者,你也可以通过将其传入 toResource 方法来指定资源类:
return User::findOrFail($id)->toResource(CustomUserResource::class);资源集合
如果你要返回资源集合或分页响应,在路由或控制器中创建资源实例时,应使用资源类提供的 collection 方法:
use App\Http\Resources\UserResource;
use App\Models\User;
Route::get('/users', function () {
return UserResource::collection(User::all());
});或者,为方便起见,你可以使用 Eloquent 集合的 toResourceCollection 方法,该方法会依据框架约定,自动发现模型对应的资源集合:
return User::all()->toResourceCollection();调用 toResourceCollection 方法时,Laravel 会尝试在最接近模型命名空间的 Http\Resources 命名空间中,查找与模型名称匹配、且以 Collection 为后缀的资源集合。
如果你的资源集合类未遵循此命名约定,或位于不同的命名空间,你可以使用 UseResourceCollection 特性为模型指定默认资源集合:
<?php
namespace App\Models;
use App\Http\Resources\CustomUserCollection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Attributes\UseResourceCollection;
#[UseResourceCollection(CustomUserCollection::class)]
class User extends Model
{
// ...
}或者,你也可以通过将其传入 toResourceCollection 方法来指定资源集合类:
return User::all()->toResourceCollection(CustomUserCollection::class);自定义资源集合
默认情况下,资源集合不允许添加任何需要随集合一并返回的自定义元数据。如果你想自定义资源集合响应,可以创建一个专用资源来表示该集合:
php artisan make:resource UserCollection资源集合类生成后,你可以轻松定义应包含在响应中的任何元数据:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;
class UserCollection extends ResourceCollection
{
/**
* 将资源集合转换为数组。
*
* @return array<int|string, mixed>
*/
public function toArray(Request $request): array
{
return [
'data' => $this->collection,
'links' => [
'self' => 'link-value',
],
];
}
}定义好资源集合后,即可在路由或控制器中返回:
use App\Http\Resources\UserCollection;
use App\Models\User;
Route::get('/users', function () {
return new UserCollection(User::all());
});或者,为方便起见,你可以使用 Eloquent 集合的 toResourceCollection 方法,该方法会依据框架约定,自动发现模型对应的资源集合:
return User::all()->toResourceCollection();调用 toResourceCollection 方法时,Laravel 会尝试在最接近模型命名空间的 Http\Resources 命名空间中,查找与模型名称匹配、且以 Collection 为后缀的资源集合。
保留集合键
从路由返回资源集合时,Laravel 会重置集合的键,使其按数字顺序排列。不过,你可以在资源类上使用 PreserveKeys 特性,以指示是否保留集合的原始键:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Attributes\PreserveKeys;
use Illuminate\Http\Resources\Json\JsonResource;
#[PreserveKeys]
class UserResource extends JsonResource
{
// ...
}当 preserveKeys 属性设置为 true 时,在路由或控制器返回集合时将保留集合键:
use App\Http\Resources\UserResource;
use App\Models\User;
Route::get('/users', function () {
return UserResource::collection(User::all()->keyBy->id);
});自定义底层资源类
通常情况下,资源集合的 $this->collection 属性会自动填充集合中每个项映射到其单一资源类的结果。单一资源类默认为集合类名去掉末尾的 Collection 部分。此外,根据个人偏好,单一资源类可能会带有 Resource 后缀,也可能不带。
例如,UserCollection 会尝试将给定的用户实例映射到 UserResource 资源。若要自定义此行为,可在资源集合上使用 Collects 特性:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Attributes\Collects;
use Illuminate\Http\Resources\Json\ResourceCollection;
#[Collects(Member::class)]
class UserCollection extends ResourceCollection
{
// ...
}编写资源
如果你尚未阅读概念概述,强烈建议你在继续阅读本文档前先阅读相关内容。
资源只需要将给定的模型转换为数组。因此,每个资源都包含一个 toArray 方法,该方法会将模型的属性转换为适合 API 的数组,可从应用程序的路由或控制器中返回:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
/**
* 将资源转换为数组。
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}定义好资源后,可直接从路由或控制器中返回:
use App\Models\User;
Route::get('/user/{id}', function (string $id) {
return User::findOrFail($id)->toResource();
});关联关系
若希望在响应中包含关联资源,可将其添加到资源 toArray 方法返回的数组中。在本示例中,我们将使用 PostResource 资源的 collection 方法,将用户的博客文章添加到资源响应中:
use App\Http\Resources\PostResource;
use Illuminate\Http\Request;
/**
* 将资源转换为数组。
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'posts' => PostResource::collection($this->posts),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
} 如果只想在关联关系已被加载时才包含它们,请参阅有关条件性关联的文档。
资源集合
资源可将单个模型转换为数组,而资源集合则可将模型集合转换为数组。不过,并非必须为每个模型都定义资源集合类,因为所有 Eloquent 模型集合都提供了 toResourceCollection 方法,可即时生成“临时”资源集合:
use App\Models\User;
Route::get('/users', function () {
return User::all()->toResourceCollection();
});然而,如果需要自定义随集合返回的元数据,则必须定义自己的资源集合类:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;
class UserCollection extends ResourceCollection
{
/**
* 将资源集合转换为数组。
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'data' => $this->collection,
'links' => [
'self' => 'link-value',
],
];
}
}与单一资源一样,资源集合可直接从路由或控制器中返回:
use App\Http\Resources\UserCollection;
use App\Models\User;
Route::get('/users', function () {
return new UserCollection(User::all());
});或者,为方便起见,你可以使用 Eloquent 集合的 toResourceCollection 方法,该方法会依据框架约定自动查找模型对应的资源集合:
return User::all()->toResourceCollection();调用 toResourceCollection 方法时,Laravel 会尝试在与模型命名空间最接近的 Http\Resources 命名空间中,查找与模型名称匹配且以 Collection 结尾的资源集合。
数据封装
默认情况下,当资源响应转换为 JSON 时,最外层资源会被封装入 data 键中。因此,典型的资源集合响应如下所示:
{
"data": [
{
"id": 1,
"name": "Eladio Schroeder Sr.",
"email": "[email protected]"
},
{
"id": 2,
"name": "Liliana Mayert",
"email": "[email protected]"
}
]
}若要禁用最外层资源的封装,应在基础类 Illuminate\Http\Resources\Json\JsonResource 上调用 withoutWrapping 方法。通常,应在 AppServiceProvider 或另一个服务提供者中调用此方法,且该服务提供者会在应用程序的每个请求中被加载:
<?php
namespace App\Providers;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* 注册应用程序服务。
*/
public function register(): void
{
// ...
}
/**
* 引导应用程序服务。
*/
public function boot(): void
{
JsonResource::withoutWrapping();
}
} withoutWrapping 方法仅影响最外层的响应,不会移除你手动添加到自有资源集合中的 data 键。
封装嵌套资源
你可以完全自由地决定资源关联关系的封装方式。若希望所有资源集合都用 data 键进行封装,无论其嵌套层级如何,应为每个资源定义资源集合类,并在 data 键内返回该集合。
你可能想知道,这样做是否会导致最外层资源被封装在两个 data 键中。不用担心,Laravel 绝不会让资源被意外重复封装,因此无需担心正在转换的资源集合的嵌套层级:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class CommentsCollection extends ResourceCollection
{
/**
* 将资源集合转换为数组。
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return ['data' => $this->collection];
}
}数据封装与分页
当通过资源响应返回分页集合时,即使已调用 withoutWrapping 方法,Laravel 仍会将资源数据封装在 data 键中。这是因为分页响应始终包含带有分页器状态信息的 meta 和 links 键:
{
"data": [
{
"id": 1,
"name": "Eladio Schroeder Sr.",
"email": "[email protected]"
},
{
"id": 2,
"name": "Liliana Mayert",
"email": "[email protected]"
}
],
"links":{
"first": "http://example.com/users?page=1",
"last": "http://example.com/users?page=1",
"prev": null,
"next": null
},
"meta":{
"current_page": 1,
"from": 1,
"last_page": 1,
"path": "http://example.com/users",
"per_page": 15,
"to": 10,
"total": 10
}
}分页
你可以将 Laravel 分页器实例传递给资源的 collection 方法,或者自定义资源集合:
use App\Http\Resources\UserCollection;
use App\Models\User;
Route::get('/users', function () {
return new UserCollection(User::paginate());
});或者,为了方便起见,您可以使用分页器的 toResourceCollection 方法,该方法将依据框架约定,自动查找分页模型底层的资源集合:
return User::paginate()->toResourceCollection();分页响应始终包含带有分页器状态信息的 meta 和 links 键:
{
"data": [
{
"id": 1,
"name": "Eladio Schroeder Sr.",
"email": "[email protected]"
},
{
"id": 2,
"name": "Liliana Mayert",
"email": "[email protected]"
}
],
"links":{
"first": "http://example.com/users?page=1",
"last": "http://example.com/users?page=1",
"prev": null,
"next": null
},
"meta":{
"current_page": 1,
"from": 1,
"last_page": 1,
"path": "http://example.com/users",
"per_page": 15,
"to": 10,
"total": 10
}
}自定义分页信息
如果您想自定义分页响应中 links 或 meta 键所包含的信息,可以在资源上定义一个 paginationInformation 方法。该方法会接收 $paginated 数据以及 $default 信息数组,其中 $default 是一个包含 links 和 meta 键的数组:
/**
* 自定义资源的分页信息。
*
* @param \Illuminate\Http\Request $request
* @param array $paginated
* @param array $default
* @return array
*/
public function paginationInformation($request, $paginated, $default)
{
$default['links']['custom'] = 'https://example.com';
return $default;
}条件属性
有时,您可能希望仅在满足特定条件时,才在资源响应中包含某个属性。例如,您可能希望仅在当前用户为“管理员”时才包含某个值。Laravel 为此提供了多种辅助方法。您可以使用 when 方法,有条件地将属性添加到资源响应中:
/**
* 将资源转换为数组。
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'secret' => $this->when($request->user()->isAdmin(), 'secret-value'),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}在此示例中,只有当已认证用户的 isAdmin 方法返回 true 时,secret 键才会出现在最终的资源响应中。如果该方法返回 false,secret 键会在发送给客户端之前,从资源响应中移除。when 方法使您能够以更富表现力的方式定义资源,而在构建数组时无需借助条件语句。
when 方法还支持将闭包作为其第二个参数,这样只有在给定条件为 true 时,才会计算最终值:
'secret' => $this->when($request->user()->isAdmin(), function () {
return 'secret-value';
}),可以使用 whenHas 方法,当基础模型上确实存在某个属性时,才将其包含进来:
'name' => $this->whenHas('name'),此外,可以使用 whenNotNull 方法,当属性不为 null 时,将其包含在资源响应中:
'name' => $this->whenNotNull($this->name),合并条件属性
有时,您可能有一些属性,只有在满足相同条件时,才应将其包含在资源响应中。在这种情况下,您可以使用 mergeWhen 方法,仅当给定条件为 true 时,才将这些属性包含在响应中:
/**
* 将资源转换为数组。
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
$this->mergeWhen($request->user()->isAdmin(), [
'first-secret' => 'value',
'second-secret' => 'value',
]),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}同样,如果给定条件为 false,这些属性会在发送给客户端之前,从资源响应中移除。
mergeWhen 方法不应在混合使用字符串键和数字键的数组中使用。此外,它也不应在键值不是按顺序排列的数字键数组中使用。
条件关联
除了有条件地加载属性外,您还可以根据模型上是否已经加载了某个关联,有条件地将该关联包含在资源响应中。这能让控制器决定要在模型上加载哪些关联,而资源则可以轻松地仅在实际加载了这些关联时才将其包含进来。最终,这能让您更轻松地避免资源中出现“N+1”查询问题。
可以使用 whenLoaded 方法有条件地加载关联。为了避免不必要的关联加载,该方法接收的是关联的名称,而非关联本身:
use App\Http\Resources\PostResource;
/**
* 将资源转换为数组。
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'posts' => PostResource::collection($this->whenLoaded('posts')),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}在此示例中,如果该关联尚未加载,posts 键会在发送给客户端之前,从资源响应中移除。
条件关联计数
除了有条件地包含关联外,您还可以根据模型上是否已经加载了关联的“计数”,有条件地在资源响应中包含关联计数:
new UserResource($user->loadCount('posts'));可以使用 whenCounted 方法,有条件地在资源响应中包含关联的计数。如果关联的计数不存在,该方法可避免不必要地包含该属性:
/**
* 将资源转换为数组。
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'posts_count' => $this->whenCounted('posts'),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}在此示例中,如果 posts 关联的计数尚未加载,posts_count 键会在发送给客户端之前,从资源响应中移除。
其他类型的聚合操作,如 avg、sum、min 和 max,也可以使用 whenAggregated 方法进行有条件加载:
'words_avg' => $this->whenAggregated('posts', 'words', 'avg'),
'words_sum' => $this->whenAggregated('posts', 'words', 'sum'),
'words_min' => $this->whenAggregated('posts', 'words', 'min'),
'words_max' => $this->whenAggregated('posts', 'words', 'max'),条件中间表信息
除了有条件地在资源响应中包含关联信息外,还可以使用 whenPivotLoaded 方法,有条件地包含来自多对多关系中间表的数据。whenPivotLoaded 方法的第一个参数为中间表的名称。第二个参数应为一个闭包,若模型上存在中间表信息,该闭包会返回要返回的值:
/**
* 将资源转换为数组。
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'expires_at' => $this->whenPivotLoaded('role_user', function () {
return $this->pivot->expires_at;
}),
];
}如果你的关联关系使用了 自定义中间表模型,你可以将中间表模型的一个实例作为第一个参数传递给 whenPivotLoaded 方法:
'expires_at' => $this->whenPivotLoaded(new Membership, function () {
return $this->pivot->expires_at;
}),如果你的中间表使用的访问器不是 pivot,可以使用 whenPivotLoadedAs 方法:
/**
* 将资源转换为数组。
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'expires_at' => $this->whenPivotLoadedAs('subscription', 'role_user', function () {
return $this->subscription->expires_at;
}),
];
}添加元数据
一些 JSON API 标准要求在资源和资源集合的响应中添加元数据。这通常包括指向资源或相关资源的 links,或者关于资源本身的元数据。如果你需要返回关于资源的额外元数据,请将其包含在 toArray 方法中。例如,在转换资源集合时,你可能要包含 links 信息:
/**
* 将资源转换为数组。
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'data' => $this->collection,
'links' => [
'self' => 'link-value',
],
];
}在从资源返回额外元数据时,你无需担心无意中覆盖 Laravel 在返回分页响应时自动添加的 links 或 meta 键。你定义的任何额外 links 都会与分页器提供的链接合并。
顶层元数据
有时你可能希望仅当资源是返回的最外层资源时,才在资源响应中包含某些元数据。通常,这包括关于整个响应的元信息。要定义这种元数据,请在资源类中添加一个 with 方法。该方法应返回一个元数据数组,仅当资源是被转换的最外层资源时,才会将该数组包含在资源响应中:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class UserCollection extends ResourceCollection
{
/**
* 将资源集合转换为数组。
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return parent::toArray($request);
}
/**
* 获取应随资源数组一起返回的额外数据。
*
* @return array<string, mixed>
*/
public function with(Request $request): array
{
return [
'meta' => [
'key' => 'value',
],
];
}
}在构造资源时添加元数据
你也可以在路由或控制器中构造资源实例时添加顶层数据。所有资源都可用的 additional 方法接受一个数据数组,这些数据会被添加到资源响应中:
return User::all()
->load('roles')
->toResourceCollection()
->additional(['meta' => [
'key' => 'value',
]]);JSON:API 资源
Laravel 自带 JsonApiResource,这是一个能生成符合 JSON:API 规范 响应的资源类。它继承自标准的 JsonResource 类,可自动处理资源对象结构、关联关系、稀疏字段集、包含项、属性的延迟求值,并将 Content-Type 请求头设置为 application/vnd.api+json。
Laravel 的 JSON:API 资源负责对响应进行序列化。如果你还需要解析传入的 JSON:API 查询参数(如过滤器和排序),Spatie 的 Laravel Query Builder 是一款出色的配套包。
生成 JSON:API 资源
要生成一个 JSON:API 资源,使用带有 --json-api 标志的 make:resource Artisan 命令:
php artisan make:resource PostResource --json-api生成的类将继承 Illuminate\Http\Resources\JsonApi\JsonApiResource,并包含用于你定义的 $attributes 和 $relationships 属性:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\JsonApi\JsonApiResource;
class PostResource extends JsonApiResource
{
/**
* 资源的属性。
*/
public $attributes = [
// ...
];
/**
* 资源的关联关系。
*/
public $relationships = [
// ...
];
}JSON:API 资源可以像标准资源一样从路由和控制器返回:
use App\Http\Resources\PostResource;
use App\Models\Post;
Route::get('/api/posts/{post}', function (Post $post) {
return new PostResource($post);
});或者,为方便起见,你可以使用模型的 toResource 方法:
Route::get('/api/posts/{post}', function (Post $post) {
return $post->toResource();
});这将生成符合 JSON:API 规范的响应:
{
"data": {
"id": "1",
"type": "posts",
"attributes": {
"title": "Hello World",
"body": "This is my first post."
}
}
}要返回 JSON:API 资源的集合,可以使用 collection 方法或 toResourceCollection 便捷方法:
return PostResource::collection(Post::all());
return Post::all()->toResourceCollection();定义属性
有两种方法可以定义 JSON:API 资源中包含哪些属性。
最简单的方法是在资源上定义一个 $attributes 属性。你可以将属性名称列为值,这些属性会直接从底层模型中读取:
public $attributes = [
'title',
'body',
'created_at',
];如果计算某个属性开销较大,你可以将其作为闭包从 toAttributes 返回,这样它只有在响应中真正需要该属性时才会被求值。
或者,若要完全控制资源的属性,你可以重写资源上的 toAttributes 方法:
/**
* 获取资源的属性。
*
* @return array<string, mixed>
*/
public function toAttributes(Request $request): array
{
return [
'title' => $this->title,
'body' => $this->body,
'is_published' => fn () => $this->published_at !== null,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}定义关联关系
JSON:API 资源支持定义遵循 JSON:API 规范的关联关系。关联关系只有在客户端通过 include 查询参数请求时才会被序列化。
$relationships 属性
你可以通过资源上的 $relationships 属性定义资源中可包含的关联关系:
public $relationships = [
'author',
'comments',
];当将关联关系名称列为值时,Laravel 会解析相应的 Eloquent 关联关系,并自动发现合适的资源类。如果你需要显式指定资源类,可以将关联关系定义为键 / 类的配对形式:
use App\Http\Resources\UserResource;
public $relationships = [
'author' => UserResource::class,
'comments',
];或者,你也可以重写资源上的 toRelationships 方法:
/**
* 获取资源的关联关系。
*/
public function toRelationships(Request $request): array
{
return [
'author' => UserResource::class,
'comments' => fn () => CommentResource::collection(
$request->user()->is($this->resource)
? $this->comments
: $this->comments->where('is_public', true),
),
];
}使用闭包可以让你更灵活地控制关联关系的负载,同时仍仅在客户端请求时才解析关联关系。
包含关联关系
客户端可以使用 include 查询参数请求相关资源:
GET /api/posts/1?include=author,comments这会生成一个在 relationships 键中包含资源标识符对象,并在顶层 included 数组中包含完整资源对象的响应:
{
"data": {
"id": "1",
"type": "posts",
"attributes": {
"title": "Hello World"
},
"relationships": {
"author": {
"data": {
"id": "1",
"type": "users"
}
},
"comments": {
"data": [
{
"id": "1",
"type": "comments"
}
]
}
}
},
"included": [
{
"id": "1",
"type": "users",
"attributes": {
"name": "Taylor Otwell"
}
},
{
"id": "1",
"type": "comments",
"attributes": {
"body": "Great post!"
}
}
]
}嵌套关系可通过点号表示法包含:
GET /api/posts/1?include=comments.author关系深度
默认情况下,嵌套关系包含的深度上限会被限制。你通常可以在应用的某个服务提供者中使用 maxRelationshipDepth 方法自定义该限制:
use Illuminate\Http\Resources\JsonApi\JsonApiResource;
JsonApiResource::maxRelationshipDepth(3);资源类型与 ID
默认情况下,资源的 type 会从资源类名派生而来。例如,PostResource 会生成 posts 类型,BlogPostResource 会生成 blog_posts 类型。资源的 id 则从模型的主键解析得到。
若需要自定义这些值,你可以在资源中覆盖 toType 和 toId 方法:
/**
* Get the resource's type.
*/
public function toType(Request $request): string
{
return 'articles';
}
/**
* Get the resource's ID.
*/
public function toId(Request $request): string
{
return (string) $this->uuid;
}当资源的类型应区别于其类名时,这尤为有用,例如当 AuthorResource 包装 User 模型且应输出 authors 类型时。
稀疏字段集与包含
JSON:API 资源支持稀疏字段集,允许客户端通过 fields 查询参数,仅为每个资源类型请求特定属性:
GET /api/posts?fields[posts]=title,created_at&fields[users]=name此配置将仅包含 posts 资源的 title 和 created_at 属性,以及 users 资源的 name 属性。
忽略查询字符串
若你希望对特定资源响应禁用稀疏字段集筛选,可调用 ignoreFieldsAndIncludesInQueryString 方法:
return $post->toResource()
->ignoreFieldsAndIncludesInQueryString();包含先前加载的关系
默认情况下,只有通过 include 查询参数请求时,关系才会被包含在响应中。若你希望无论查询字符串如何,都包含所有先前预加载的关系,可调用 includePreviouslyLoadedRelationships 方法:
return $post->load('author', 'comments')
->toResource()
->includePreviouslyLoadedRelationships();链接与元数据
你可以通过在资源中覆盖 toLinks 和 toMeta 方法,为 JSON:API 资源对象添加链接和元信息:
/**
* Get the resource's links.
*/
public function toLinks(Request $request): array
{
return [
'self' => route('api.posts.show', $this->resource),
];
}
/**
* Get the resource's meta information.
*/
public function toMeta(Request $request): array
{
return [
'readable_created_at' => $this->created_at->diffForHumans(),
];
}这会在响应的资源对象中添加 links 和 meta 键:
{
"data": {
"id": "1",
"type": "posts",
"attributes": {
"title": "Hello World"
},
"links": {
"self": "https://example.com/api/posts/1"
},
"meta": {
"readable_created_at": "2 hours ago"
}
}
}资源响应
正如你已了解的,可直接从路由和控制器返回资源:
use App\Models\User;
Route::get('/user/{id}', function (string $id) {
return User::findOrFail($id)->toResource();
});然而,有时你可能需要先自定义即将发送给客户端的 HTTP 响应,可通过两种方式实现。第一种,在资源上链式调用 response 方法,该方法会返回 Illuminate\Http\JsonResponse 实例,让你能完全控制响应头:
use App\Http\Resources\UserResource;
use App\Models\User;
Route::get('/user', function () {
return User::find(1)
->toResource()
->response()
->header('X-Value', 'True');
});另一种方式是在资源内部定义 withResponse 方法,当资源作为响应中最外层资源返回时,该方法会被调用:
<?php
namespace App\Http\Resources;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
/**
* 将资源转换为数组。
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
];
}
/**
* 自定义资源的出站响应。
*/
public function withResponse(Request $request, JsonResponse $response): void
{
$response->header('X-Value', 'True');
}
}