From e4ea782242a65d8c0b6d07fc6fc43da6eda659ea Mon Sep 17 00:00:00 2001 From: Andrew Date: Mon, 26 Jun 2017 18:38:24 -0500 Subject: [PATCH] documentation on default relationship models --- eloquent-relationships.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/eloquent-relationships.md b/eloquent-relationships.md index c1f91a1a9a..af7be9c38d 100644 --- a/eloquent-relationships.md +++ b/eloquent-relationships.md @@ -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'; + }); + } + + ### One To Many