Posts Learn Components Snippets Categories Tags Tools About
/

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

Learn how to prevent an error when accessing a property that has no relation

Created on Aug 17, 2021

706 views

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.

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

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Sponsors 👑

+ Add Yours
)