Blog

Laravel - Null Object pattern

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

Before

User model with has one country relationship:

public function country()
{
    return $this->hasOne(\App\Models\Country::class, 'id', 'country_id');
}

View:

{{ $user->country ? $user->country->name : '-' }}

After

User model with has one country relationship and default model:

public function country()
{
    return $this->hasOne(\App\Models\Country::class, 'id', 'country_id')->withDefault([
        'name' => '-'
    ]);
}

View:

{{ $user->country->name }}
Zoeken