NewWe open-sourced 50+ Laravel packages
Custom AI apps, agents and automation — Roundly ConsultingRoundly
All packages
Credits for Laravel

Reading balances

balance() sums the ledger rows of one bucket. Pass a point in time to reconstruct the balance as it stood then — only rows with created_at at or before that moment count. has() compares the balance with an amount, 1 by default:

Credits::for($user)->balance();                                // 70 — the default bucket
Credits::for($user)->balance(now()->subWeek());                // as of a point in time
Credits::for($user)->bucket('promotional')->balance(now()->startOfMonth());

Credits::for($user)->has(100);                                 // true if balance >= 100
Credits::for($user)->bucket('purchased')->has(100, now()->subWeek());

The trait forms are creditsBalance() and hasCredits():

$user->creditsBalance();                         // 70 — the default bucket

// Balance as of a point in time (rows with created_at <= $at):
$user->creditsBalance(now()->subWeek());
$user->creditsBalance(at: now()->startOfMonth(), bucket: 'promotional');

Checking available credits

hasCredits() compares the balance with an amount — 1 by default — and accepts the same point-in-time and bucket arguments:

$user->hasCredits();                             // true if balance >= 1
$user->hasCredits(100);                          // true if balance >= 100
$user->hasCredits(100, now()->subWeek());        // ... as of a week ago
$user->hasCredits(100, bucket: 'purchased');     // ... in one bucket

has() and hasCredits() are reads, not reservations. To spend safely, deduct() and let the overdraft guard decide under its locks.

The ledger relation

credits() is a standard MorphMany relationship, so the underlying rows are a query away:

$user->credits()->latest()->get();              // every ledger row, newest first
$user->credits()->deductions()->count();         // the model's query scopes work on the relation
$user->credits()->withTrashed()->get();          // include soft-deleted rows

Credit uses soft deletes. A deleted row stays in the table but no longer counts toward any balance, and it is hidden from the relation unless you ask for withTrashed().

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

By 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.