When dealing with relationships in Laravel, you might often find yourself checking if a related model exists before accessing its properties. Laravel provides a withDefault()
method to return a default model with attributes if the relationship is null, allowing you to avoid those null checks.
class Post extends Model
{
public function author(): BelongsTo
{
return $this->belongsTo(User::class)->withDefault([
'name' => 'Guest Author',
]);
}
}
With this setup, even if a Post doesnβt have an associated author, you can safely access the name attribute without worrying about null values:
echo $post->author->name; // Outputs 'Guest Author' if no user is associated