Posts Learn Components Snippets Categories Tags 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

22 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.

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

new

PostSrc Code Components

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

View Components

Other Code Snippets

More