イントロダクション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ケース(Upper Camel
Case)」で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 accessor, 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
内部プロパティーへ加工済みの値を設定します。ではSally
をfirst_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_at
とupdated_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
)、日付時間文字列、それにもちろんDateTime
やCarbon
インスタンスを値としてセットでき、日付は自動的に正しくデータベースへ保存されます。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
プロパティーは配列で、キーにはキャストする属性名を指定し、値にはそのカラムに対してキャストしたいタイプを指定します。サポートしているキャストタイプはinteger
、real
、float
、double
、string
、boolean
、object
、array
、collection
、date
、datetime
、timestamp
です。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
.
例としてデータベースには整数の0
と1
で保存されている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を持つJSON
かTEXT
フィールドがある場合、その属性に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();