Eloquent: 序列化
介绍
在使用 Laravel 构建 API 时,您通常需要将模型和关系转换为数组或 JSON。Eloquent 提供了方便的方法来进行这些转换,并控制哪些属性包含在模型的序列化表示中。
如果需要更强大的方式来处理 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
{
/**
* 应该在数组中隐藏的属性。
*
* @var array
*/
protected $hidden = ['password'];
}
要隐藏关系,请将关系的方法名称添加到 Eloquent 模型的 $hidden
属性中。
或者,您可以使用 visible
属性定义一个“允许列表”,其中包含应包含在模型的数组和 JSON 表示中的属性。所有不在 $visible
数组中的属性在模型转换为数组或 JSON 时将被隐藏:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* 应该在数组中可见的属性。
*
* @var array
*/
protected $visible = ['first_name', 'last_name'];
}
临时修改属性可见性
如果您希望在给定的模型实例上使一些通常隐藏的属性可见,可以使用 makeVisible
方法。makeVisible
方法返回模型实例:
return $user->makeVisible('attribute')->toArray();
同样,如果您希望隐藏一些通常可见的属性,可以使用 makeHidden
方法。
return $user->makeHidden('attribute')->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
{
/**
* 确定用户是否为管理员。
*
* @return \Illuminate\Database\Eloquent\Casts\Attribute
*/
protected function isAdmin(): Attribute
{
return new Attribute(
get: fn () => 'yes',
);
}
}
创建访问器后,将属性名称添加到模型的 appends
属性中。请注意,属性名称通常使用其“蛇形命名法”序列化表示,即使访问器的 PHP 方法是使用“驼峰命名法”定义的:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* 要附加到模型数组形式的访问器。
*
* @var array
*/
protected $appends = ['is_admin'];
}
一旦将属性添加到 appends
列表中,它将包含在模型的数组和 JSON 表示中。appends
数组中的属性也将遵循模型上配置的 visible
和 hidden
设置。
运行时附加
在运行时,您可以使用 append
方法指示模型实例附加其他属性。或者,您可以使用 setAppends
方法覆盖给定模型实例的整个附加属性数组:
return $user->append('is_admin')->toArray();
return $user->setAppends(['is_admin'])->toArray();
日期序列化
自定义默认日期格式
您可以通过重写 serializeDate
方法来自定义默认的序列化格式。此方法不会影响日期在数据库中的存储格式:
/**
* 准备日期以进行数组 / JSON 序列化。
*
* @param \DateTimeInterface $date
* @return string
*/
protected function serializeDate(DateTimeInterface $date)
{
return $date->format('Y-m-d');
}
自定义每个属性的日期格式
您可以通过在模型的类型声明中指定日期格式来自定义单个 Eloquent 日期属性的序列化格式:
protected $casts = [
'birthday' => 'date:Y-m-d',
'joined_at' => 'datetime:Y-m-d H:00',
];