[Laravel] withDefaultを使用した関連モデルの初期化
Eloquentモデルにおいて、belongsToでリレーションを行なっているモデルが存在しない場合にNULLが返却されていましたが、モデルのインスタンスを返却できるメソッドwithDefaultが追加されました。
関連するユーザーモデルが存在しない場合に、ユーザーモデルのインスタンスが返却されます。
php
/**
* Get the author of the post.
*/
public function user()
{
return $this->belongsTo('App\User')->withDefault();
}また、初期値を代入することが可能です。
php
/**
* Get the author of the post.
*/
public function user()
{
return $this->belongsTo('App\User')->withDefault([
'name' => 'Guest Author',
]);
}
/**
* Get the author of the post.
*/
public function user()
{
return $this->belongsTo('App\User')->withDefault(function ($user) {
$user->name = 'Guest Author';
});
}