雄辩:序列化
Introduction
使用 Laravel 构建 API 时,您通常需要将模型和关系转换为数组或 JSON。 Eloquent 包括方便的方法来进行这些转换,以及控制哪些属性包含在模型的序列化表示中。
Note
如需更强大的处理 Eloquent 模型和集合 JSON 序列化的方法,请查看文档雄辩的 API 资源.
序列化模型和集合
序列化到数组
转换模型及其加载relationships 到一个数组,你应该使用toArray 方法。这个方法是递归的,所以所有的属性和所有的关系(包括关系的关系)都会被转换为数组:
use App\Models\User;
$user = User::with('roles')->first();
return $user->toArray();
这attributesToArray 方法可用于将模型的属性转换为数组而不是其关系:
$user = User::first();
return $user->attributesToArray();
您也可以将整个collections 通过调用将模型转换为数组toArray 集合实例上的方法:
$users = User::all();
return $users->toArray();
序列化为 JSON
要将模型转换为 JSON,您应该使用toJson 方法。喜欢toArray, 这toJson 方法是递归的,因此所有属性和关系都将转换为 JSON。您还可以指定任何 JSON 编码选项支持PHP:
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();
});
Relationships
当 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 arrays.
*
* @var array
*/
protected $hidden = ['password'];
}
Note
要隐藏关系,请将关系的方法名称添加到 Eloquent 模型的$hidden财产。
或者,您可以使用visible 属性来定义应包含在模型数组和 JSON 表示中的属性的“允许列表”。中不存在的所有属性$visible 当模型转换为数组或 JSON 时,数组将被隐藏:
<?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 方法。这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 时,您可能希望添加在数据库中没有对应列的属性。为此,首先定义一个accessor 对于价值:
<?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 方法。或者,您可以使用setAppends 覆盖给定模型实例的整个附加属性数组的方法:
return $user->append('is_admin')->toArray();
return $user->setAppends(['is_admin'])->toArray();
日期序列化
自定义默认日期格式
您可以通过覆盖serializeDate 方法。此方法不会影响您的日期在数据库中存储的格式:
/**
* Prepare a date for array / JSON serialization.
*/
protected function serializeDate(DateTimeInterface $date): string
{
return $date->format('Y-m-d');
}
自定义每个属性的日期格式
您可以通过在模型中指定日期格式来自定义单个 Eloquent 日期属性的序列化格式转换声明:
protected $casts = [
'birthday' => 'date:Y-m-d',
'joined_at' => 'datetime:Y-m-d H:00',
];