Readouble

Laravel 10.x Eloquent: シリアライズ

イントロダクションIntroduction

Laravelを使用してAPIを構築する場合、モデルとリレーションを配列またはJSONに変換する必要が頻繁にあります。Eloquentには、これらの変換を行うための便利な方法と、モデルのシリアル化された表現に含まれる属性を制御するための便利な方法が含まれています。When building APIs using Laravel, you will often need to convert your models and relationships to arrays or JSON. Eloquent includes convenient methods for making these conversions, as well as controlling which attributes are included in the serialized representation of your models.

lightbulb Note: EloquentモデルとコレクションのJSONシリアル化を処理するさらに堅牢な方法については、Eloquent APIリソースのドキュメントを確認してください。[!NOTE]
For an even more robust way of handling Eloquent model and collection JSON serialization, check out the documentation on Eloquent API resources[/docs/{{version}}/eloquent-resources].

モデルとコレクションのシリアル化Serializing Models and Collections

配列へのシリアル化Serializing to Arrays

モデルとそのロードされたリレーションを配列へ変換するには、toArrayメソッドを使用する必要があります。このメソッドは再帰的であるため、すべての属性とすべてのリレーション(リレーションのリレーションを含む)を配列へ変換します。To convert a model and its loaded relationships[/docs/{{version}}/eloquent-relationships] to an array, you should use the toArray method. This method is recursive, so all attributes and all relations (including the relations of relations) will be converted to arrays:

use App\Models\User;

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

return $user->toArray();

attributesToArrayメソッドを使用して、モデルの属性を配列に変換できますが、そのリレーションは変換できません。The attributesToArray method may be used to convert a model's attributes to an array but not its relationships:

$user = User::first();

return $user->attributesToArray();

コレクションインスタンスでtoArrayメソッドを呼び出すことにより、モデルのコレクション全体を配列へ変換することもできます。You may also convert entire collections[/docs/{{version}}/eloquent-collections] of models to arrays by calling the toArray method on the collection instance:

$users = User::all();

return $users->toArray();

JSONへのシリアル化Serializing to JSON

モデルをJSONに変換するには、toJsonメソッドを使用する必要があります。toArrayと同様に、toJsonメソッドは再帰的であるため、すべての属性とリレーションはJSONに変換されます。PHPがサポートしているJSONエンコーディングオプションを指定することもできます。To convert a model to JSON, you should use the toJson method. Like toArray, the toJson method is recursive, so all attributes and relations will be converted to JSON. You may also specify any JSON encoding options that are supported by PHP[https://secure.php.net/manual/en/function.json-encode.php]:

use App\Models\User;

$user = User::find(1);

return $user->toJson();

return $user->toJson(JSON_PRETTY_PRINT);

もしくは、モデルまたはコレクションを文字列にキャストすると、モデルまたはコレクションのtoJsonメソッドが自動的に呼び出されます。Alternatively, you may cast a model or collection to a string, which will automatically call the toJson method on the model or collection:

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

モデルとコレクションは文字列にキャストされるとJSONに変換されるため、アプリケーションのルートまたはコントローラから直接Eloquentオブジェクトを返すことができます。Laravelはルートまたはコントローラから返されるときに、EloquentモデルコレクションをJSONへ自動的にシリアル化します。Since models and collections are converted to JSON when cast to a string, you can return Eloquent objects directly from your application's routes or controllers. Laravel will automatically serialize your Eloquent models and collections to JSON when they are returned from routes or controllers:

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

リレーションRelationships

EloquentモデルをJSONに変換すると、ロードずみのリレーションは自動的にJSONオブジェクトの属性として含まれます。また、Eloquentリレーションシップメソッドは「キャメルケース」メソッド名を使用して定義されますが、リレーションシップのJSON属性は「スネークケース」になります。When an Eloquent model is converted to JSON, its loaded relationships will automatically be included as attributes on the JSON object. Also, though Eloquent relationship methods are defined using "camel case" method names, a relationship's JSON attribute will be "snake case".

JSONから属性を隠すHiding Attributes From JSON

モデルの配列またはJSON表現に含まれるパスワードなどの属性を制限したい場合があります。これには、モデルへ$hiddenプロパティを追加します。$hiddenプロパティの配列にリストされている属性は、モデルのシリアル化された表現には含まれません。Sometimes you may wish to limit the attributes, such as passwords, that are included in your model's array or JSON representation. To do so, add a $hidden property to your model. Attributes that are listed in the $hidden property's array will not be included in the serialized representation of your model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * 配列に対して非表示にする必要がある属性
     *
     * @var array
     */
    protected $hidden = ['password'];
}

lightbulb Note: リレーションを非表示にするには、リレーションのメソッド名をEloquentモデルの$hiddenプロパティに追加します。[!NOTE]
To hide relationships, add the relationship's method name to your Eloquent model's $hidden property.

もしくは、visibleプロパティを使用して、モデルの配列とJSON表現に含める必要のある属性の「許可リスト」を定義することもできます。モデルが配列またはJSONに変換されると、$visible配列に存在しないすべての属性が非表示になります。Alternatively, you may use the visible property to define an "allow list" of attributes that should be included in your model's array and JSON representation. All attributes that are not present in the $visible array will be hidden when the model is converted to an array or JSON:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * 配列に表示する属性
     *
     * @var array
     */
    protected $visible = ['first_name', 'last_name'];
}

属性の可視性を一時的に変更Temporarily Modifying Attribute Visibility

特定のモデルインスタンスで通常は非表示になっている属性を表示したい場合は、makeVisibleメソッドを使用します。makeVisibleメソッドはモデルインスタンスを返します:If you would like to make some typically hidden attributes visible on a given model instance, you may use the makeVisible method. The makeVisible method returns the model instance:

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

同様に、通常表示される一部の属性を非表示にする場合は、makeHiddenメソッドを使用します。Likewise, if you would like to hide some attributes that are typically visible, you may use the makeHidden method.

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

一時的にすべてのvisible属性やhidden属性を上書きしたい場合は、setVisibleメソッドやsetHiddenメソッドが使用できます。If you wish to temporarily override all of the visible or hidden attributes, you may use the setVisible and setHidden methods respectively:

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

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

JSONへ値の追加Appending Values to JSON

モデルを配列またはJSONに変換するときに、データベースに対応するカラムがない属性を追加したい場合もまれにあります。これを行うには、最初に値のアクセサを定義します。Occasionally, when converting models to arrays or JSON, you may wish to add attributes that do not have a corresponding column in your database. To do so, first define an accessor[/docs/{{version}}/eloquent-mutators] for the value:

<?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メソッドは「キャメルケース」で定義することに注意しましょう。If you would like the accessor to always be appended to your model's array and JSON representations, you may add the attribute name to the appends property of your model. Note that attribute names are typically referenced using their "snake case" serialized representation, even though the accessor's PHP method is defined using "camel case":

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * モデルの配列フォームに追加するアクセサ
     *
     * @var array
     */
    protected $appends = ['is_admin'];
}

属性をappendsリストへ追加すると、モデルの配列とJSON表現の両方に含まれます。appends配列の属性は、モデルで設定されたvisibleおよびhidden設定も尊重します。Once the attribute has been added to the appends list, it will be included in both the model's array and JSON representations. Attributes in the appends array will also respect the visible and hidden settings configured on the model.

実行時の追加Appending at Run Time

実行時に、appendメソッドを使用して追加の属性を追加するようにモデルインスタンスに指示できます。または、setAppendsメソッドを使用して、特定のモデルインスタンスに追加されたプロパティの配列全体をオーバーライドすることもできます。At runtime, you may instruct a model instance to append additional attributes using the append method. Or, you may use the setAppends method to override the entire array of appended properties for a given model instance:

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

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

日付のシリアル化Date Serialization

デフォルトの日付形式のカスタマイズCustomizing the Default Date Format

serializeDateメソッドをオーバーライドすることにより、デフォルトのシリアル化形式をカスタマイズできます。この方法は、データベースに保存するために日付をフォーマットする方法には影響しません。You may customize the default serialization format by overriding the serializeDate method. This method does not affect how your dates are formatted for storage in the database:

/**
 * 配列/JSONシリアル化の日付の準備
 */
protected function serializeDate(DateTimeInterface $date): string
{
    return $date->format('Y-m-d');
}

属性ごとの日付形式のカスタマイズCustomizing the Date Format per Attribute

モデルのキャスト定義で日付形式を指定することにより、個々のEloquent日付属性のシリアル化形式をカスタマイズできます。You may customize the serialization format of individual Eloquent date attributes by specifying the date format in the model's cast declarations[/docs/{{version}}/eloquent-mutators#attribute-casting]:

protected $casts = [
    'birthday' => 'date:Y-m-d',
    'joined_at' => 'datetime:Y-m-d H:00',
];

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作