Skip to content

Commit

Permalink
Add default models example for method style
Browse files Browse the repository at this point in the history
  • Loading branch information
bennothommo authored Jul 29, 2024
1 parent e0f4393 commit a3801a9
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion database/relations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand All @@ -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:
Expand Down

0 comments on commit a3801a9

Please sign in to comment.