How to prevent “property of non-object” error

1// BelongsTo Default Models
2// Let's say you have Post belonging to Author and then Blade code:
3$post->author->name;
4 
5// Of course, you can prevent it like this:
6$post->author->name ?? ''
7// or
8@$post->author->name
9 
10// But you can do it on Eloquent relationship level:
11// this relation will return an empty App\Author model if no author is attached to the post
12public function author() {
13 return $this->belongsTo('App\Author')->withDefault();
14}
15// or
16public function author() {
17 return $this->belongsTo('App\Author')->withDefault([
18 'name' => 'Guest Author'
19 ]);
20}

Tip given by @coderahuljat

Like our articles?

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