イントロダクション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.
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'];
}
Note: リレーションを非表示にするには、リレーションのメソッド名をEloquentモデルの
$hiddenプロパティに追加します。[!NOTE]
To hide relationships, add the relationship's method name to your Eloquent model's$hiddenproperty.
もしくは、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 function casts(): array
{
return [
'birthday' => 'date:Y-m-d',
'joined_at' => 'datetime:Y-m-d H:00',
];
}