Laravel - Relationships - Default Models
The belongsTo
, hasOne
, hasOneThrough
, and morphOne
relationships allow you to define a default model that will be returned if the given relationship is null
. This pattern is often referred to as the Null Object pattern and can help remove conditional checks in your code. In the following example, the user
relation will return an empty App\Models\User
model if no user is attached to the Post
model:
/**
* Get the author of the post.
*/
public function user()
{
return $this->belongsTo(User::class)->withDefault();
}
To populate the default model with attributes, you may pass an array or closure to the withDefault
method:
/**
* Get the author of the post.
*/
public function user()
{
return $this->belongsTo(User::class)->withDefault([
'name' => 'Guest Author',
]);
}
/**
* Get the author of the post.
*/
public function user()
{
return $this->belongsTo(User::class)->withDefault(function ($user, $post) {
$user->name = 'Guest Author';
});
}