Readouble

Laravel 5.2 Eloquent:シリアライズ

イントロダクションIntroduction

JSONでAPIを作成する場合にはモデルとリレーションを配列やJSONに変換する必要が良く起きます。そのためEloquentはシリアライズ結果にどの属性を含むかをコントロールしながら、変換を行う便利なメソッドを含んでいますWhen building JSON APIs, 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 your serializations.

基本的な使用法Basic Usage

モデルを配列へ変換Converting A Model To An Array

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

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

return $user->toArray();

コレクションを配列に変換することもできます。You may also convert collections[/docs/{{version}}/eloquent-collections] to arrays:

$users = App\User::all();

return $users->toArray();

モデルをJSONへ変換Converting A Model To JSON

モデルをJSONへ変換するにはtoJsonメソッドを使います。toArrayと同様にtoJsonメソッドは再帰的に動作し、全属性と全リレーションをJSONへ変換します。To convert a model to JSON, you may use the toJson method. Like toArray, the toJson method is recursive, so all attributes and relations will be converted to JSON:

$user = App\User::find(1);

return $user->toJson();

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

$user = App\User::find(1);

return (string) $user;

文字列にキャストする場合、モデルやコレクションはJSONに変換されますので、アプリケーションのルートやコントローラーから直接Eloquentオブジェクトを返すことができます。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:

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

JSONに含めない属性Hiding Attributes From JSON

モデルの配列やJSONに、パスワードのような属性を含めたくない場合があります。それにはモデルの$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 definition to your model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     *  配列に含めない属性
     *
     * @var array
     */
    protected $hidden = ['password'];
}

注意: リレーションを含めない場合は、リレーションの動的プロパティー名ではなくメソッド名を指定してください。Note: When hiding relationships, use the relationship's method name, not its dynamic property name.

もしくはモデルの配列やJSONに含めるべき属性のホワイトリストを定義するvisibleプロパティーを使用してください。Alternatively, you may use the visible property to define a white-list of attributes that should be included in your model's array and JSON representation:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

プロパティ配列出力管理の一時的変更Temporarily Modifying Property Visibility

特定のモデルインスタンスにおいて、通常は配列に含めない属性を含めたい場合は、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 for convenient method chaining:

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

同様に、通常は含める属性を特定のインスタンスで隠したい場合は、makeHiddenメソッドを使います。Likewise, if you would like to make some typically visible attributes hidden on a given model instance, you may use the makeHidden method.

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

JSONへ値を追加Appending Values To JSON

データベースに対応するカラムがない属性の配列を追加する必要がある場合も時々あります。これを行うには、最初にその値のアクセサを定義します。Occasionally, you may need to add array 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;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * ユーザーの管理者フラッグを取得
     *
     * @return bool
     */
    public function getIsAdminAttribute()
    {
        return $this->attributes['admin'] == 'yes';
    }
}

アクセサができたらモデルのappendsプロパティーへ属性名を追加します。Once you have created the accessor, add the attribute name to the appends property on the model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

appendsリストに属性を追加すれば、モデルの配列とJSON形式両方に含まれるようになります。appends配列の属性もモデルのvisiblehiddenの設定に従い動作します。Once the attribute has been added to the appends list, it will be included in both the model's array and JSON forms. Attributes in the appends array will also respect the visible and hidden settings configured on the model.

章選択

設定

明暗テーマ
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!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

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

コードフォント

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

保存内容リセット

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

ヘッダー項目移動

キーボード操作