BelongsTo Default Models: No Need to Check in Blade Files

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:

And then somewhere in Blade file we have this:

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:

Or you can perform a check for existence:

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.

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.

By using this structure, you don’t need to check anything in Blade anymore – just have the same

where needed.

Source: official Laravel documentation (look for section Default Models)

Want to generate Laravel adminpanel online?
You don't need any packages to do that!

7 thoughts on “BelongsTo Default Models: No Need to Check in Blade Files

  1. {{ $post->user ? $post->user->name : $post->name }}

    return $this->belongsTo(‘App\User’)->withDefault([‘name’=>$this->name]);

  2. Really nice tip, but this applies only to belongsTo relationships, right? I normally don’t need checks for these; I’d love to be to skip checks for other relationships, such as belongsToMany.

Leave a Reply

Your email address will not be published. Required fields are marked *