Readouble

Laravel master Eloquent:ミューテタ

イントロダクションIntroduction

アクセサとミューテタはモデルの取得や値を設定するときに、Eloquent属性のフォーマットを可能にします。たとえばLaravelの暗号化を使いデータベース保存時に値を暗号化し、Eloquentモデルでアクセスする時には自動的にその属性を復元するように設定できます。Accessors and mutators allow you to format Eloquent attribute values when you retrieve or set them on model instances. For example, you may want to use the Laravel encrypter[/docs/{{version}}/encryption] to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model.

カスタムのアクセサやミューテタに加え、Eloquentは日付フールドを自動的にCarbonインスタンスにキャストしますし、テキストフィールドをJSONにキャストすることもできます。In addition to custom accessors and mutators, Eloquent can also automatically cast date fields to Carbon[https://github.com/briannesbitt/Carbon] instances or even cast text fields to JSON[#attribute-casting].

アクセサとミューテタAccessors & Mutators

アクセサの定義Defining An Accessor

アクセサを定義するには、アクセスしたいカラム名が「studlyケース」でFooの場合、getFooAttributeメソッドをモデルに作成します。以下の例では、first_name属性のアクセサを定義しています。first_name属性の値にアクセスが起きると、Eloquentは自動的にこのアクセサを呼び出します。To define an accessor, create a getFooAttribute method on your model where Foo is the "studly" cased name of the column you wish to access. In this example, we'll define an accessor for the first_name attribute. The accessor will automatically be called by Eloquent when attempting to retrieve the value of the first_name attribute:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * ユーザのファーストネームを取得
     *
     * @param  string  $value
     * @return string
     */
    public function getFirstNameAttribute($value)
    {
        return ucfirst($value);
    }
}

ご覧の通り、アクセサにはそのカラムのオリジナルの値が渡されますので、それを加工し値を返します。ミューテタの値にアクセスするには通常通りに、モデルインスタンスのfirst_name属性へアクセスしてください。As you can see, the original value of the column is passed to the accessor, allowing you to manipulate and return the value. To access the value of the mutator, you may simply access the first_name attribute on a model instance:

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

$firstName = $user->first_name;

ミューテタの定義Defining A Mutator

ミューテタを定義するにはアクセスしたいカラム名がFooの場合、モデルに「ローワーキャメルケース」でsetFooAttributeメソッドを作成します。今回もfirst_name属性を取り上げ、ミューテタを定義しましょう。このミューテタはモデルのfirst_name属性へ値を設定する時に自動的に呼びだされます。To define a mutator, define a setFooAttribute method on your model where Foo is the "studly" cased name of the column you wish to access. So, again, let's define a mutator for the first_name attribute. This mutator will be automatically called when we attempt to set the value of the first_name attribute on the model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * ユーザのファーストネームを設定
     *
     * @param  string  $value
     * @return void
     */
    public function setFirstNameAttribute($value)
    {
        $this->attributes['first_name'] = strtolower($value);
    }
}

ミューテタは属性に設定しようとしている値を受け取りますのでこれを加工し、Eloquentモデルの$attributes内部プロパティーへ加工済みの値を設定します。ではSallyfirst_name属性へ設定してみましょう。The mutator will receive the value that is being set on the attribute, allowing you to manipulate the value and set the manipulated value on the Eloquent model's internal $attributes property. So, for example, if we attempt to set the first_name attribute to Sally:

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

$user->first_name = 'Sally';

上記の場合、setFirstNameAttributeメソッドが呼び出され、Sallayの値が渡されます。このミューテタはそれから名前にstrtolowerを適用し、その値を$attributes内部配列へ設定します。In this example, the setFirstNameAttribute function will be called with the value Sally. The mutator will then apply the strtolower function to the name and set its resulting value in the internal $attributes array.

日付ミューテタDate Mutators

デフォルトでEloquentはcreated_atupdated_atカラムをCarbonインスタンスへ変換します。CarbonはPHPネイティブのDateTimeクラスを拡張しており、便利なメソッドを色々と提供しています。モデルの$datesプロパティーをオーバーライドすることで、どのフィールドを自動的に変形するのか、逆にこのミューテタを適用しないのかをカスタマイズできます。By default, Eloquent will convert the created_at and updated_at columns to instances of Carbon[https://github.com/briannesbitt/Carbon], which extends the PHP DateTime class to provide an assortment of helpful methods. You may customize which dates are automatically mutated, and even completely disable this mutation, by overriding the $dates property of your model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * 日付を変形する属性
     *
     * @var array
     */
    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at'
    ];
}

カラムが日付だと推定される場合、値はUnixタイムスタンプ、日付文字列(Y-m-d)、日付時間文字列、それにもちろんDateTimeCarbonインスタンスを値としてセットでき、日付は自動的に正しくデータベースへ保存されます。When a column is considered a date, you may set its value to a UNIX timestamp, date string (Y-m-d), date-time string, and of course a DateTime / Carbon instance, and the date's value will automatically be correctly stored in your database:

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

$user->deleted_at = Carbon::now();

$user->save();

前記の通り$datesプロパティーにリストした属性を取得する場合、自動的にCarbonインスタンスへキャストされますので、その属性でCarbonのメソッドがどれでも使用できます。As noted above, when retrieving attributes that are listed in your $dates property, they will automatically be cast to Carbon[https://github.com/briannesbitt/Carbon] instances, allowing you to use any of Carbon's methods on your attributes:

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

return $user->deleted_at->getTimestamp();

DateフォーマットDate Formats

デフォルトのタイムスタンプフォーマットは'Y-m-d H:i:s'です。タイムスタンプフォーマットをカスタマイズする必要があるなら、モデルの$dateFormatプロパティを設定してください。このプロパティは日付属性がデータベースにどのように保存されるかと同時に、モデルが配列やJSONにシリアライズされる時のフォーマットを決定します。By default, timestamps are formatted as 'Y-m-d H:i:s'. If you need to customize the timestamp format, set the $dateFormat property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
    /**
     * モデルの日付カラムの保存形式
     *
     * @var string
     */
    protected $dateFormat = 'U';
}

属性キャストAttribute Casting

モデルの$castsプロパティーは属性を一般的なデータタイプへキャストする便利な手法を提供します。$castsプロパティーは配列で、キーにはキャストする属性名を指定し、値にはそのカラムに対してキャストしたいタイプを指定します。サポートしているキャストタイプはintegerrealfloatdoublestringbooleanobjectarraycollectiondatedatetimetimestampです。The $casts property on your model provides a convenient method of converting attributes to common data types. The $casts property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to. The supported cast types are: integer, real, float, double, string, boolean, object, array, collection, date, datetime, and timestamp.

例としてデータベースには整数の01で保存されているis_admin属性を論理値にキャストしてみましょう。For example, let's cast the is_admin attribute, which is stored in our database as an integer (0 or 1) to a boolean value:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * ネイティブなタイプへキャストする属性
     *
     * @var array
     */
    protected $casts = [
        'is_admin' => 'boolean',
    ];
}

これでデータベースには整数で保存されていてもis_admin属性にアクセスすれば、いつでも論理値にキャストされます。Now the is_admin attribute will always be cast to a boolean when you access it, even if the underlying value is stored in the database as an integer:

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

if ($user->is_admin) {
    //
}

配列とJSONのキャストArray & JSON Casting

arrayキャストタイプは、シリアライズされたJSON形式で保存されているカラムを取り扱うときに特に便利です。たとえば、データベースにシリアライズ済みのJSONを持つJSONTEXTフィールドがある場合、その属性にarrayキャストを追加すれば、Eloquentモデルにアクセスされた時点で自動的に非シリアライズ化され、PHPの配列へとキャストされます。The array cast type is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a JSON or TEXT field type that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * ネイティブなタイプへキャストする属性
     *
     * @var array
     */
    protected $casts = [
        'options' => 'array',
    ];
}

キャストを定義後、options属性にアクセスすると自動的に非シリアライズされPHP配列になります。options属性へ値をセットすると配列は保存のために自動的にJSONへシリアライズされます。Once the cast is defined, you may access the options attribute and it will automatically be deserialized from JSON into a PHP array. When you set the value of the options attribute, the given array will automatically be serialized back into JSON for storage:

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

$options = $user->options;

$options['key'] = 'value';

$user->options = $options;

$user->save();

章選択

開発環境
ビューとテンプレート
公式パッケージ

設定

明暗テーマ
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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作