Skip to content

Commit

Permalink
documentation on default relationship models
Browse files Browse the repository at this point in the history
  • Loading branch information
browner12 committed Jun 26, 2017
1 parent d0bc4eb commit e4ea782
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions eloquent-relationships.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,43 @@ If your parent model does not use `id` as its primary key, or you wish to join t
return $this->belongsTo('App\User', 'foreign_key', 'other_key');
}

#### Default Models

If a relationship can be nullable, it is often helpful to return a default model, rather than `null`. This is often referred to as the Null Object Pattern, which can help remove a lot of conditional checks in your views.

/**
* Get the author of the blog
*/
public function user()
{
return $this->belongsTo('App\User')->withDefault();
}

If the `user_id` is `null` on the `blogs` table, you will receive back an `App\User` model.

You may also pass an array or a closure to the method to customize the properties of the default model.

/**
* Get the author of the blog
*/
public function user()
{
return $this->belongsTo('App\User')->withDefault([
'name' => 'Guest Author',
]);
}

/**
* Get the author of the blog
*/
public function user()
{
return $this->belongsTo('App\User')->withDefault(function ($user) {
$user->name => 'Guest Author';
});
}

<a name="one-to-many"></a>
### One To Many

Expand Down

0 comments on commit e4ea782

Please sign in to comment.