withDefault(): Prevent “property of non-object” error

// BelongsTo Default Models
// Let's say you have Post belonging to Author and then Blade code:
$post->author->name;
 
// Of course, you can prevent it like this:
$post->author->name ?? ''
// or
@$post->author->name
 
// But you can do it on Eloquent relationship level:
// this relation will return an empty App\Author model if no author is attached to the post
public function author() {
return $this->belongsTo(Author::class)->withDefault();
}
// or
public function author() {
return $this->belongsTo(Author::class)->withDefault([
'name' => 'Guest Author'
]);
}

Tip given by @coderahuljat

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 59 courses (1057 lessons, total 42 h 44 min)
  • 79 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials