TIP 54 / 100

How to Prevent “Property of Non-object” Error.

code
// Provide a default model for a belongsTo relationship.
// For example, a post may belong to an author and be displayed in Blade:
$post->author->name;

// You can guard against a missing author with this check:
$post->author->name ?? ''
// or
@$post->author->name

// Define the fallback directly on the Eloquent relationship:
// The relationship returns an empty Author model when the post has no author.
public function author() {
    return $this->belongsTo(Author::class)->withDefault();
}
// or
public function author() {
    return $this->belongsTo(Author::class)->withDefault([
        'name' => 'Guest Author'
    ]);
}