From a3801a9fa5232e7ea95ccf1dd4614159c7aebeb0 Mon Sep 17 00:00:00 2001 From: Ben Thomson Date: Mon, 29 Jul 2024 14:30:40 +0800 Subject: [PATCH] Add default models example for method style --- database/relations.md | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/database/relations.md b/database/relations.md index d20f731c..e7d86cce 100644 --- a/database/relations.md +++ b/database/relations.md @@ -332,7 +332,7 @@ public function user(): BelongsTo #### Default models -The `belongsTo` relationship lets you 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](https://en.wikipedia.org/wiki/Null_Object_pattern) and can help remove conditional checks in your code. In the following example, the `user` relation will return an empty `Acme\Blog\Models\User` model if no `user` is attached to the post: +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](https://en.wikipedia.org/wiki/Null_Object_pattern) and can help remove conditional checks in your code. In the following example, the `user` relation will return an empty `Acme\Blog\Models\User` model if no `user` is attached to the post: ```php public $belongsTo = [ @@ -351,6 +351,24 @@ public $belongsTo = [ ]; ``` +If you have defined the relation as a method, you may use the `withDefault()` method to define a default model: + +```php +public function user(): BelongsTo +{ + return $this->belongsTo('Acme\Blog\Models\User')->withDefault(); +} + +// With attributes + +public function user(): BelongsTo +{ + return $this->belongsTo('Acme\Blog\Models\User')->withDefault([ + 'name' => 'Guest', + ]); +} +``` + ### One To Many A one-to-many relationship is used to define relationships where a single model owns any amount of other models. For example, a blog post may have an infinite number of comments. Like all other relationships, one-to-many relationships are defined adding an entry to the `$hasMany` property on your model: