Home / Snippets / How to Prevent an Error When Accessing null Property in Laravel Relation
How to Prevent an Error When Accessing null Property in Laravel Relation cover

How to Prevent an Error When Accessing null Property in Laravel Relation

724

3 years ago

0 comments

To prevent getting an error when accessing a model that has no relation, you can provide a default value when a model currently has no relation. This default value is available for the belongsTo, hasOne, hasOneThrough, and morphOne relationships.

withDefault() Code Example

/**
 * Get the author of the post.
 */
public function user()
{
    return $this->belongsTo(User::class)->withDefault();
}
By doing so, when the model has no relation, accessing any of its properties will not cause an error.

Populate Default Model With Attribute


To populate the default value, you can pass in an associative array of attributes and values like below. Otherwise, you can pass in a closure and you can populate the value as shown.
/**
 * Get the author of the post.
 */
public function user()
{
    return $this->belongsTo(User::class)->withDefault([
        'name' => 'Guest Author',
    ]);
}

/**
 * Get the author of the post.
 */
public function user()
{
    return $this->belongsTo(User::class)->withDefault(function ($user, $post) {
        $user->name = 'Guest Author';
    });
}
For more details do refer to Laravel Default Value Documentation.
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this