---
title: "withDefault() - ніяких null при зв'язках"
url: https://laravelukraine.com/blog/withdefault-niiakix-null-pri-zviazkax
date: 2026-08-12
---

# withDefault() - ніяких null при зв'язках

Постійно перевіряєте, чи існує зв'язок, перед доступом до нього?

`withDefault()` повертає "порожню" модель замість null.

**Переваги:**

* Менше `if ($user->profile)`
* Чистіші Blade-шаблони
* Можливість задати дефолтні значення

```php
// User model
public function profile()
{
  return $this->hasOne(Profile::class)
    ->withDefault([
      'bio' => 'No bio provided',
      'avatar' => 'default.png',
      'website' => null,
    ]);
}

// Без перевірок на null
{{ $user->profile->bio }}
```

```php
// Динамічні дефолти
public function profile()
{
  return $this->hasOne(Profile::class)
    ->withDefault(function ($profile, $user) {
      $profile->bio = "Member since {$user->created_at->year}";
    });
}

// BelongsTo з дефолтом
public function author()
{
  return $this->belongsTo(User::class, 'author_id')
    ->withDefault([
      'name' => 'Guest',
      'email' => 'noreply@example.com',
    ]);
}

// У Blade
{{ $post->author->name }} // Ніколи не null
```
