Eloquent:序列化
简介
使用 Laravel 构建 API 时,经常需要将模型及其关联转换为数组或 JSON。Eloquent 提供了便捷的转换方法,并可控制哪些属性会出现在模型的序列化结果中。
INFO
若需要更强大的 Eloquent 模型与集合 JSON 序列化方式,请参阅 Eloquent API 资源 文档。
序列化模型与集合
序列化为数组
要将模型及其已加载的关联转换为数组,请使用 toArray 方法。该方法是递归的,因此所有属性与所有关联(包括关联的关联)都会被转换为数组:
use App\Models\User;
$user = User::with('roles')->first();
return $user->toArray();attributesToArray 方法可将模型的属性转换为数组,但不包含其关联:
$user = User::first();
return $user->attributesToArray();你也可以在集合实例上调用 toArray,将整份模型集合转换为数组:
$users = User::all();
return $users->toArray();序列化为 JSON
要将模型转换为 JSON,请使用 toJson 方法。与 toArray 一样,toJson 也是递归的,因此所有属性与关联都会被转换为 JSON。你还可以指定 PHP 支持 的任意 JSON 编码选项:
use App\Models\User;
$user = User::find(1);
return $user->toJson();
return $user->toJson(JSON_PRETTY_PRINT);或者,你也可以将模型或集合转换为字符串,此时会自动在模型或集合上调用 toJson 方法:
return (string) User::find(1);由于模型与集合在转换为字符串时会变成 JSON,你可以直接从应用的路由或控制器返回 Eloquent 对象。从路由或控制器返回时,Laravel 会自动将 Eloquent 模型与集合序列化为 JSON:
Route::get('/users', function () {
return User::all();
});关联
当 Eloquent 模型转换为 JSON 时,已加载的关联会自动作为 JSON 对象上的属性包含进去。另外,尽管 Eloquent 关联方法使用「驼峰」命名,关联在 JSON 中的属性名会是「蛇形」命名。
从 JSON 中隐藏属性
有时你可能希望限制出现在模型数组或 JSON 表示中的属性,例如密码。为此,可在模型上添加 $hidden 属性。列在 $hidden 属性数组中的属性不会出现在模型的序列化结果中:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The attributes that should be hidden for serialization.
*
* @var array<string>
*/
protected $hidden = ['password'];
}INFO
若要隐藏关联,请将关联的方法名加入 Eloquent 模型的 $hidden 属性。
或者,你可以使用 visible 属性定义应包含在模型数组与 JSON 表示中的属性「允许列表」。模型转换为数组或 JSON 时,未出现在 $visible 数组中的属性都会被隐藏:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The attributes that should be visible in arrays.
*
* @var array
*/
protected $visible = ['first_name', 'last_name'];
}临时修改属性可见性
若希望在某个模型实例上让通常隐藏的属性可见,可使用 makeVisible 或 mergeVisible 方法。makeVisible 会返回模型实例:
return $user->makeVisible('attribute')->toArray();
return $user->mergeVisible(['name', 'email'])->toArray();同样,若希望隐藏通常可见的属性,可使用 makeHidden 或 mergeHidden 方法:
return $user->makeHidden('attribute')->toArray();
return $user->mergeHidden(['name', 'email'])->toArray();若希望临时覆盖全部可见或隐藏属性,可分别使用 setVisible 与 setHidden 方法:
return $user->setVisible(['id', 'name'])->toArray();
return $user->setHidden(['email', 'password', 'remember_token'])->toArray();向 JSON 追加值
有时在将模型转换为数组或 JSON 时,你可能希望添加数据库中没有对应列的属性。为此,请先为该值定义一个访问器:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Determine if the user is an administrator.
*/
protected function isAdmin(): Attribute
{
return new Attribute(
get: fn () => 'yes',
);
}
}若希望访问器始终追加到模型的数组与 JSON 表示中,可将属性名加入模型的 appends 属性。注意:即便访问器的 PHP 方法使用「驼峰」命名,属性名通常仍按其「蛇形」序列化表示引用:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = ['is_admin'];
}属性加入 appends 列表后,会出现在模型的数组与 JSON 表示中。appends 数组中的属性也会遵守模型上配置的 visible 与 hidden 设置。
运行时追加
在运行时,你可以使用 append 或 mergeAppends 方法让模型实例追加额外属性。或者,使用 setAppends 覆盖某个模型实例的全部追加属性数组:
return $user->append('is_admin')->toArray();
return $user->mergeAppends(['is_admin', 'status'])->toArray();
return $user->setAppends(['is_admin'])->toArray();同样,若要从模型中移除全部追加属性,可使用 withoutAppends 方法:
return $user->withoutAppends()->toArray();日期序列化
自定义默认日期格式
你可以通过重写 serializeDate 方法自定义默认序列化格式。该方法不会影响日期在数据库中的存储格式:
/**
* Prepare a date for array / JSON serialization.
*/
protected function serializeDate(DateTimeInterface $date): string
{
return $date->format('Y-m-d');
}按属性自定义日期格式
你可以通过在模型的转换声明中指定日期格式,来自定义各个 Eloquent 日期属性的序列化格式:
protected function casts(): array
{
return [
'birthday' => 'date:Y-m-d',
'joined_at' => 'datetime:Y-m-d H:00',
];
}