---
title: "Nested budgets — Credits for Laravel | Roundly"
description: "Nest owners — a person in a team in a company — so every debit and hold is checked and written against every parent’s balance in one transaction."
url: https://roundly-consulting.com/open-source/docs/credits-for-laravel/nested-budgets
language: en
---

[All packages](https://roundly-consulting.com/open-source.md)

[Credits for Laravel](https://roundly-consulting.com/open-source/docs/credits-for-laravel.md)

# Nested budgets

Since 2.2.0, opt-in. An owner can sit inside another one: a person inside a team inside a company. Its spending then also counts against, and is capped by, every ancestor’s balance in the same bucket. One call checks and writes the whole chain in one transaction — you no longer hold each level one after another, undo earlier holds by hand when a later one fails, or let two siblings both pass their own check and together overspend the shared parent.

## Setup

Parents are off until you switch them on. While credits.parents.enabled is off, no parent is ever looked up and every owner stands alone, exactly as before 2.2.0:

```bash
CREDITS_PARENTS=true
CREDITS_PARENTS_MAX_DEPTH=8   # optional: how many ancestors a chain may have (default 8, 1–64)
```

With holds on, also publish and run the link\_credit\_holds\_to\_their\_origin migration (see Installation). Parents without holds need no migration.

## Naming a parent

Implement HasCreditParent on the owner:

```php
use RoundlyConsulting\Credits\Interfaces\Creditable;
use RoundlyConsulting\Credits\Interfaces\HasCreditParent;
use RoundlyConsulting\Credits\Traits\HasCredits;

final class Member extends Model implements Creditable, HasCreditParent
{
    use HasCredits;

    public function creditParent(): ?Team
    {
        return $this->team; // null at the top
    }
}
```

Or register one resolver for every owner, for models you cannot change. It takes precedence over creditParent() for every owner, so hand the others back to their own method:

```php
Credits::resolveParentsUsing(fn ($owner) => $owner instanceof User
    ? $owner->currentTeam
    : ($owner instanceof HasCreditParent ? $owner->creditParent() : null));

Credits::resolveParentsUsing(null); // remove it
```

A parent must itself be Model&Creditable, and its ledger must live on the same connection as the child’s, because one transaction covers the whole chain.

## What each operation does on a chain

available is a bucket’s balance minus its active holds, as everywhere in the package. Every level is guarded against credits.minimum\_balance unless the call allows an overdraft:

| Operation | Checked against | Written on |
| --- | --- | --- |
| `hold($amount)` | every level’s available balance | every level: the returned hold plus a linked hold on each ancestor |
| `modify(-$amount) / deduct()` | every level’s available balance | every level: one ledger row each |
| `setTo()` lowering the balance | every level, for the delta | every level, the delta |
| `modify(+$amount) / add() / setTo()` raising the balance | — | the owner only |
| `capture($hold, $amount)` | — (the hold reserved it) | every level: each hold captured, one debit each |
| `capture(…, allowOverdraft: true)` beyond the hold | — | every level, the full amount |
| `release($hold)` | — | every level’s hold released |
| `expireHolds()` | — | a hold’s levels expire together, in one transaction |
| `reset()` | the owner only | the owner only — a reset never touches its parents |

setTo() is checked and written on every level only when it lowers the balance; raising it touches the owner alone. A child whose own budget is higher than its parent’s is still capped by the parent:

```php
// company 100, team 1 000, person 1 000
Credits::availableWithin($person)->available;  // 100
Credits::for($person)->hold(101);              // InsufficientCreditsException, naming the company
```

## Holds: one per level

A hold on an owner with parents is one hold row per level. The hold the call returns is the origin (chain\_depth 0). Each ancestor gets a linked hold (chain\_depth 1, 2, …) whose origin\_hold\_id points back at it, with the same amount, bucket, expiry, description and meta. Every level’s held() and available() count its own hold, so the parent’s balance reflects every child’s reservation without any extra query. Capture, release and expiry read a hold’s levels with their owners eager-loaded, so they work under Model::preventLazyLoading() (since 2.2.1).

Resolve a hold through its origin: capture() and release() on a linked level throw LinkedCreditHoldException. $hold->isLinked() and $hold->originKey() tell them apart. A level that was resolved on its own meanwhile is skipped.

## Locking

Every chain write locks the owners from the top down: root first, then each level down to the owner. Two writes on sibling owners therefore queue on their shared parent, and the second decides on the balance the first left behind — exactly one of two siblings racing for the parent’s last credits gets them, on every isolation level. Opposite-order requests cannot deadlock, because no write takes a child before its parent. It is the same credit\_locks mechanism as for a single owner (see Overdraft protection), proven on Postgres by the package’s two-session race tests.

## Reading — availableWithin()

```php
$within = Credits::availableWithin($person, 'ai');   // or Credits::for($person)->bucket('ai')->availableWithin()

$within->available;                   // the smallest available balance along the chain
$within->limitedBy;                   // the owner that has it (the nearest one on a tie)
$within->limitedByParent($person);    // true when an ancestor sets the limit
$within->levels;                      // owners in the chain, the person included
```

It is a read, not a promise: hold the amount to keep it. Without parents, or with parents off, it is the owner’s own available().

## When a level refuses

InsufficientCreditsException names the owner that blocked:

```php
use RoundlyConsulting\Credits\Exceptions\InsufficientCreditsException;

try {
    Credits::for($person)->hold(500);
} catch (InsufficientCreditsException $e) {
    $e->creditable;          // the blocking owner (a parent, or the person itself)
    $e->requestedBy;         // the person the call was made on
    $e->blockedByParent();   // true when a parent blocked
    $e->ownerType();         // the blocking owner's morph type
    $e->ownerKey();          // its key
    $e->available;           // what that owner had available
    $e->requested;           // -500
}
```

Levels are checked from the owner upward, so the nearest owner that blocks is named. A parent’s refusal reads “Insufficient credits in the budget of \[App\\Models\\Team#7\]: tried to deduct 500 but only 120 are available there.” (credits::messages.insufficient\_within\_parent, English and Slovak); a refusal by the owner itself keeps the existing messages. InvalidCreditParentException is thrown when a chain cannot be walked — a cycle, more ancestors than credits.parents.max\_depth, or a parent whose ledger lives on another connection — and nothing is written.

## Events

Each fires once per level that changed, with that level’s owner, so the app can send per-level “budget warning” or “budget reached” notices:

- CreditsHeld($creditable, $hold, $available), where $available is that level’s available balance after the hold.
- CreditsModified($creditable, $credit, $balance) for every level’s debit, a capture’s included.
- CreditHoldCaptured($creditable, $hold, $credit, $released).
- CreditHoldReleased($hold) and CreditHoldExpired($hold).

## Testing with the fake

Credits::fake() walks parents the way the ledger does: a debit or hold on a child is checked and recorded on every level, so you can assert per level:

```php
$fake = Credits::fake();

Credits::for($person)->hold(40);

$fake->assertHeld($company, 40);
$fake->assertHeld($person, 40);
Credits::availableWithin($person)->limitedBy; // read from the fake's balances
```

## Switching parents off

Switch them off only once no hold made on an owner with parents is still active: a hold’s linked levels are only resolved while parents are on.

## Show your open-source love

This package is free and MIT-licensed. If it saves you time, a one-off donation or a Patreon membership keeps it maintained, tested and documented.

[More ways to support, including crypto](https://roundly-consulting.com/support-us.md)

By donating, you agree to our [donation terms](https://roundly-consulting.com/donation-terms.md).

[Support our open source work (opens in a new tab)](https://donate.stripe.com/dRmeVe8FX5PF1Qd9pXcEw00) [Join us on Patreon (opens in a new tab)](https://www.patreon.com/cw/roundly)

## Want this built into your product?

We integrate our packages into custom Laravel and AI builds. Tell us what you're working on and we'll reply within 48 hours.

[Get a quote in 48 hours](https://roundly-consulting.com/contact.md) [Browse all packages](https://roundly-consulting.com/open-source/docs/credits-for-laravel.md)
