Skip to content

Eloquent: 序列化

简介

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

NOTE

要获得更强大的 Eloquent 模型和集合 JSON 序列化处理方式,请查看 Eloquent API 资源文档。

序列化模型和集合

序列化为数组

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

php
use App\Models\User;

$user = User::with('roles')->first();

return $user->toArray();

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

php
$user = User::first();

return $user->attributesToArray();

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

php
$users = User::all();

return $users->toArray();

序列化为 JSON

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

php
use App\Models\User;

$user = User::find(1);

return $user->toJson();

return $user->toJson(JSON_PRETTY_PRINT);

或者,你可以将模型或集合转换为字符串,这将自动调用模型或集合上的 toJson 方法:

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

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

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

关联关系

当 Eloquent 模型转换为 JSON 时,其加载的关联关系将自动作为属性包含在 JSON 对象中。此外,虽然 Eloquent 关联关系方法使用「驼峰命名」方法名定义,但关系的 JSON 属性将采用「蛇形命名」。

在 JSON 中隐藏属性

有时你可能希望限制模型数组或 JSON 表示中包含的属性,例如密码。为此,可以在模型上使用 Hidden 属性。Hidden 属性中列出的属性将不会包含在模型的序列化表示中:

php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Model;

#[Hidden(['password'])]
class User extends Model
{
    // ...
}

NOTE

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

或者,你可以使用 Visible 属性定义模型数组和 JSON 表示中应包含的属性的「允许列表」。所有不存在于 Visible 属性中的属性在模型转换为数组或 JSON 时将被隐藏:

php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Visible;
use Illuminate\Database\Eloquent\Model;

#[Visible(['first_name', 'last_name'])]
class User extends Model
{
    // ...
}

临时修改属性可见性

如果你想在给定模型实例上显示一些通常隐藏的属性,可以使用 makeVisiblemergeVisible 方法。makeVisible 方法返回模型实例:

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

return $user->mergeVisible(['name', 'email'])->toArray();

同样,如果你想隐藏一些通常可见的属性,可以使用 makeHiddenmergeHidden 方法:

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

return $user->mergeHidden(['name', 'email'])->toArray();

如果你想临时覆盖所有可见或隐藏的属性,可以分别使用 setVisiblesetHidden 方法:

php
return $user->setVisible(['id', 'name'])->toArray();

return $user->setHidden(['email', 'password', 'remember_token'])->toArray();

在 JSON 中追加值

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

php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * 确定用户是否是管理员。
     */
    protected function isAdmin(): Attribute
    {
        return new Attribute(
            get: fn () => 'yes',
        );
    }
}

如果你希望访问器始终附加到模型的数组和 JSON 表示中,可以在模型上使用 Appends 属性。请注意,属性名通常使用其「蛇形命名」序列化表示引用,即使访问器的 PHP 方法使用「驼峰命名」定义:

php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Appends;
use Illuminate\Database\Eloquent\Model;

#[Appends(['is_admin'])]
class User extends Model
{
    // ...
}

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

运行时追加

在运行时,你可以使用 appendmergeAppends 方法指示模型实例追加额外的属性。或者,你可以使用 setAppends 方法覆盖给定模型实例的整个追加属性数组:

php
return $user->append('is_admin')->toArray();

return $user->mergeAppends(['is_admin', 'status'])->toArray();

return $user->setAppends(['is_admin'])->toArray();

同样,如果你想从模型中删除所有追加的属性,可以使用 withoutAppends 方法:

php
return $user->withoutAppends()->toArray();

日期序列化

自定义默认日期格式

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

php
/**
 * 为数组 / JSON 序列化准备日期。
 */
protected function serializeDate(DateTimeInterface $date): string
{
    return $date->format('Y-m-d');
}

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

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

php
protected function casts(): array
{
    return [
        'birthday' => 'date:Y-m-d',
        'joined_at' => 'datetime:Y-m-d H:00',
    ];
}