How to use default Models with relationships in Laravel

Categorized as Laravel Tagged

As you may know, you can skip checking if your relationship doesn’t exist in Laravel with withDefault method. But did you know that you can also assign attributes to a default Model? See the example below:

// Model relationship
class Comment extends Model 
{
  public function author()
  {
    return $this->belongsTo(User::class)->withDefault([
      'name' => 'Guest',
    ]);
  }
}
// 😔 Now in your blade view file, instead of doing this
{{ $comment->author ? $comment->author->name : 'Guest' }}

// ✅ You can do this 
{{ $comment->author->name }}

Leave a reply

Your email address will not be published.