---
title: "whenEmpty() та whenNotEmpty() - умовні операції"
url: https://laravelukraine.com/blog/whenempty-ta-whennotempty-umovni-operaciyi
date: 2026-09-09
---

# whenEmpty() та whenNotEmpty() - умовні операції

Потрібно виконувати код лише тоді, коли колекція порожня або непорожня?
if/else роблять код об'ємним.

`whenEmpty()` та `whenNotEmpty()` роблять це чисто.

**Приклади використання:**

* Показати контент за замовчуванням
* Логувати попередження
* Запускати fallback-логіку
* Присвоювати значення за замовчуванням

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

Методи ланцюжаться та зберігають fluent-синтаксис.

Порада: значення, повернуте з callback, стає новим значенням колекції.

```php
$users = User::where('active', true)->get();

// ПОГАНО: розривається ланцюжок
if ($users->isEmpty()) {
  return redirect()->back()->with('error', 'No active users');
}

// ДОБРЕ: fluent-синтаксис
$users->whenEmpty(function () {
  return redirect()->back()->with('error', 'No active users');
});

// Додати елементи за замовчуванням, якщо порожньо
$products = Product::where('featured', true)->get();

$products = $products->whenEmpty(function ($collection) {
  return Product::latest()->limit(5)->get();
});

// Логування, якщо непорожня
$errors->whenNotEmpty(function ($collection) {
  Log::error('Validation errors found', $collection->toArray());
});

// З "else"
$users->whenEmpty(
  fn($collection) => ['name' => 'Guest'],
  fn($collection) => $collection->first()
);
```

```php
// API-відповідь із fallback
return response()->json([
  'users' => $users->whenEmpty(fn() => collect([
    ['name' => 'No users found', 'id' => null]
  ]))
]);

// Ланцюжок операцій
$results = collect($searchResults)
  ->whenEmpty(fn() => $this->getDefaultResults())
  ->take(10)
  ->map(fn($item) => $this->format($item));

// Прогрів кешу
$cached = Cache::get('popular_posts');

collect($cached)->whenEmpty(function () {
  $posts = Post::popular()->get();
  Cache::put('popular_posts', $posts, 3600);
  return $posts;
});

// Надсилання email-дайджесту
$notifications->whenNotEmpty(function ($items) {
  Mail::to($user)->send(new NotificationDigest($items));
});
```
