跳到内容

Eloquent:序列化

简介

在使用 Laravel 构建 API 时,您经常需要将模型和关系转换为数组或 JSON。 Eloquent 包含方便的方法来进行这些转换,并控制哪些属性包含在模型的序列化表示中。

为了更强大地处理 Eloquent 模型和集合 JSON 序列化,请查看关于 Eloquent API 资源的文档。

序列化模型和集合

序列化为数组

要将模型及其加载的关系转换为数组,您应该使用 toArray 方法。此方法是递归的,因此所有属性和所有关系(包括关系的关系)都将转换为数组

1use App\Models\User;
2 
3$user = User::with('roles')->first();
4 
5return $user->toArray();

attributesToArray 方法可用于将模型的属性转换为数组,但不包括其关系

1$user = User::first();
2 
3return $user->attributesToArray();

您还可以通过在集合实例上调用 toArray 方法,将整个模型集合转换为数组

1$users = User::all();
2 
3return $users->toArray();

序列化为 JSON

要将模型转换为 JSON,您应该使用 toJson 方法。与 toArray 类似,toJson 方法是递归的,因此所有属性和关系都将转换为 JSON。您还可以指定任何 PHP 支持的 JSON 编码选项

1use App\Models\User;
2 
3$user = User::find(1);
4 
5return $user->toJson();
6 
7return $user->toJson(JSON_PRETTY_PRINT);

或者,您可以将模型或集合强制转换为字符串,这将自动在模型或集合上调用 toJson 方法

1return (string) User::find(1);

由于模型和集合在强制转换为字符串时会转换为 JSON,因此您可以直接从应用程序的路由或控制器返回 Eloquent 对象。当从路由或控制器返回 Eloquent 模型和集合时,Laravel 将自动将其序列化为 JSON

1Route::get('/users', function () {
2 return User::all();
3});

关系

当 Eloquent 模型转换为 JSON 时,其加载的关系将自动作为 JSON 对象上的属性包含在内。此外,尽管 Eloquent 关系方法是使用“驼峰式”方法名称定义的,但关系的 JSON 属性将是“蛇形命名法”。

从 JSON 中隐藏属性

有时您可能希望限制模型数组或 JSON 表示中包含的属性,例如密码。为此,请向您的模型添加 $hidden 属性。$hidden 属性数组中列出的属性将不会包含在模型的序列化表示中

1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Database\Eloquent\Model;
6 
7class User extends Model
8{
9 /**
10 * The attributes that should be hidden for serialization.
11 *
12 * @var array<string>
13 */
14 protected $hidden = ['password'];
15}

要隐藏关系,请将关系的方法名称添加到 Eloquent 模型的 $hidden 属性中。

或者,您可以使用 visible 属性定义应包含在模型数组和 JSON 表示中的属性的“允许列表”。当模型转换为数组或 JSON 时,$visible 数组中不存在的所有属性都将被隐藏

1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Database\Eloquent\Model;
6 
7class User extends Model
8{
9 /**
10 * The attributes that should be visible in arrays.
11 *
12 * @var array
13 */
14 protected $visible = ['first_name', 'last_name'];
15}

临时修改属性可见性

如果您想使给定模型实例上通常隐藏的某些属性可见,您可以使用 makeVisible 方法。 makeVisible 方法返回模型实例

1return $user->makeVisible('attribute')->toArray();

同样,如果您想隐藏一些通常可见的属性,您可以使用 makeHidden 方法。

1return $user->makeHidden('attribute')->toArray();

如果您希望暂时覆盖所有可见或隐藏的属性,您可以分别使用 setVisiblesetHidden 方法

1return $user->setVisible(['id', 'name'])->toArray();
2 
3return $user->setHidden(['email', 'password', 'remember_token'])->toArray();

向 JSON 追加值

有时,在将模型转换为数组或 JSON 时,您可能希望添加在数据库中没有相应列的属性。为此,首先为该值定义一个 访问器

1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Database\Eloquent\Casts\Attribute;
6use Illuminate\Database\Eloquent\Model;
7 
8class User extends Model
9{
10 /**
11 * Determine if the user is an administrator.
12 */
13 protected function isAdmin(): Attribute
14 {
15 return new Attribute(
16 get: fn () => 'yes',
17 );
18 }
19}

如果您希望访问器始终附加到模型的数组和 JSON 表示,您可以将属性名称添加到模型的 appends 属性中。请注意,属性名称通常使用其“蛇形命名法”序列化表示来引用,即使访问器的 PHP 方法是使用“驼峰式”定义的

1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Database\Eloquent\Model;
6 
7class User extends Model
8{
9 /**
10 * The accessors to append to the model's array form.
11 *
12 * @var array
13 */
14 protected $appends = ['is_admin'];
15}

将属性添加到 appends 列表后,它将包含在模型的数组和 JSON 表示中。 appends 数组中的属性也将遵循模型上配置的 visiblehidden 设置。

在运行时追加

在运行时,您可以指示模型实例使用 append 方法追加其他属性。或者,您可以使用 setAppends 方法覆盖给定模型实例的整个追加属性数组

1return $user->append('is_admin')->toArray();
2 
3return $user->setAppends(['is_admin'])->toArray();

日期序列化

自定义默认日期格式

您可以通过覆盖 serializeDate 方法来自定义默认序列化格式。此方法不影响日期在数据库中存储的格式

1/**
2 * Prepare a date for array / JSON serialization.
3 */
4protected function serializeDate(DateTimeInterface $date): string
5{
6 return $date->format('Y-m-d');
7}

自定义每个属性的日期格式

您可以通过在模型的类型转换声明中指定日期格式来自定义各个 Eloquent 日期属性的序列化格式

1protected function casts(): array
2{
3 return [
4 'birthday' => 'date:Y-m-d',
5 'joined_at' => 'datetime:Y-m-d H:00',
6 ];
7}

Laravel 是构建最有效率的方式,可以
构建、部署和监控软件。