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:
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:
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:
Credits::resolveParentsUsing(fn ($owner) => $owner instanceof User
? $owner->currentTeam
: ($owner instanceof HasCreditParent ? $owner->creditParent() : null));
Credits::resolveParentsUsing(null); // remove itA 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:
// company 100, team 1 000, person 1 000
Credits::availableWithin($person)->available; // 100
Credits::for($person)->hold(101); // InsufficientCreditsException, naming the companyHolds: 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.
Extra ceilings — alsoWithin()
Since 2.3.0. A budget that caps the same call but is no ancestor of the owner — such as an AI agent’s own monthly budget beside the person’s team and company — is named per call:
$hold = Credits::for($person)->alsoWithin($agentBudget)->hold(40); // or new CreditHoldData(40, alsoWithin: [$agentBudget])
Credits::for($person)->alsoWithin($agentBudget)->deduct(10); // or new CreditChangeData(-10, alsoWithin: [...])
Credits::availableWithin($person, alsoWithin: [$agentBudget]); // ->limitedByCeiling- Each extra owner is a level like a parent, with its own parents too (each owner counted once). A hold writes a linked hold on it and a debit a ledger row; capture, release and expiry resolve it with the rest, and a capture beyond the hold with allowOverdraft debits it too.
- A refusal by an extra ceiling names it like a parent’s: $e->creditable is the ceiling and $e->blockedByCeiling() is true (blockedByParent() stays false).
- Extra ceilings apply whether or not parents are switched on. A grant (a positive amount) still stays with the owner. A ceiling on another ledger connection throws InvalidCreditParentException.
- Holds with extra ceilings need the link_credit_holds_to_their_origin migration from 2.2.0; debits need none.
Lock order
Every write on several owners takes their locks in one global order: nearest the top of its own chain first (a parent before its children), then by morph type and key. Two single operations sharing owners therefore always meet them in the same order and queue, whichever way they named them. One limit applies to any locking scheme: a host transaction that runs two separate holds, each on its own set of owners, can still deadlock with another such transaction. Postgres and MySQL detect it and abort one side; when the package’s own transaction is the outermost, it is retried.
Reading — availableWithin()
$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->limitedByCeiling; // true when an extra ceiling (alsoWithin()) sets it — since 2.3.0
$within->levels; // owners in the chain, the person includedIt 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:
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:
$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 balancesSwitching parents off
Since 2.3.0 a hold’s linked levels are found wherever the linking columns exist, so switching parents off no longer strands them: capture, release and expiry still resolve every level of a hold made while parents were 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 cryptoBy donating, you agree to our donation terms.
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.