Eloquent:序列化
- Introduction
- Serializing Models and Collections
- Hiding Attributes From JSON
- Appending Values to JSON
- Date Serialization
介绍
使用 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 表示中的属性。$visible
当模型转换为数组或 JSON 时,所有数组中不存在的属性都将被隐藏:
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 array13 */14 protected $visible = ['first_name', 'last_name'];15}
临时修改属性可见性
如果希望在给定的模型实例上显示一些通常隐藏的属性,可以使用该makeVisible
方法。该makeVisible
方法返回模型实例:
1return $user->makeVisible('attribute')->toArray();
同样,如果您想隐藏一些通常可见的属性,您可以使用该makeHidden
方法。
1return $user->makeHidden('attribute')->toArray();
如果您希望暂时覆盖所有可见或隐藏属性,您可以分别使用setVisible
和setHidden
方法:
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(): Attribute14 {15 return new Attribute(16 get: fn () => 'yes',17 );18 }19}
如果您希望访问器始终附加到模型的数组和 JSON 表示中,可以将属性名称添加到appends
模型的属性 (property) 中。请注意,即使访问器的 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 array13 */14 protected $appends = ['is_admin'];15}
一旦属性添加到appends
列表,它将同时包含在模型的数组和 JSON 表示中。appends
数组中的属性也将遵循模型上配置的visible
和设置。hidden
在运行时附加
在运行时,你可以使用 方法来指示模型实例附加额外的属性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): string5{6 return $date->format('Y-m-d');7}
自定义每个属性的日期格式
您可以通过在模型的强制类型声明中指定日期格式来自定义各个 Eloquent 日期属性的序列化格式:
1protected function casts(): array2{3 return [4 'birthday' => 'date:Y-m-d',5 'joined_at' => 'datetime:Y-m-d H:00',6 ];7}