Skip to main content
Tutorial Free

BelongsTo Default Models: No Need to Check in Blade Files

August 07, 2017
2 min read
I've recently found out about a feature in Laravel relationship which changed the way I write code. So sharing with you. Let's say we have a relationship in Post model:
public function author()
{
    return $this->belongsTo('App\Author');
}
And then somewhere in Blade file we have this:
{{ $post->author->name }}
Now, what if some post doesn't have author? Meaning posts.author_id is NULL. You will get an error "Trying to get property of non-object", meaning that there's no $post->author, which is correct. How I handle it usually:
{{ $post->author->name or 'No author' }}
Or you can perform a check for existence:
@if ($post->author)
  {{ $post->author->name }}
@else
  Do something else
@endif

What if I told you there's a better way?

Apparently, Eloquent relationships allow to define "default" models, in case the model wouldn't return anything.
public function author()
{
    return $this->belongsTo('App\Author')->withDefault();
}
In this example, the author() relation will return an empty App\Author model if no author is attached to the post. Furthermore, we can assign default property values to that default model.
public function author()
{
    return $this->belongsTo('App\Author')->withDefault([
        'name' => 'Guest Author',
    ]);
}
By using this structure, you don't need to check anything in Blade anymore - just have the same
{{ $post->author->name }}
where needed. Source: official Laravel documentation (look for section Default Models)

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

Laravel Modules and DDD

16 lessons
1 h 59 min

PhpStorm Junie AI for Laravel Projects: Crash Course

7 lessons
36 min

NativePHP: Build Mobile App with Laravel

11 lessons
2 h 2 min read

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.