一个基于账本的 Laravel 包,用于管理应用程序中的基于信用的系统。
Your logo here — Become a sponsor and get your logo featured in this README and on our website.
Interested in title sponsorship? Contact us at [email protected] for premium placement and recognition.
You can install the package via composer:
composer require climactic/laravel-creditsPublish and run the migrations:
php artisan vendor:publish --tag="credits-migrations"
php artisan migrateOptionally publish the config file:
php artisan vendor:publish --tag="credits-config"return [
// Allow negative balances
'allow_negative_balance' => false,
// Table name for credit transactions (change if you've updated the migration table name)
'table_name' => 'credits',
];Concurrency & Locking: This package uses row-level locking (SELECT FOR UPDATE) to prevent race conditions during concurrent credit operations. This requires a database engine that supports proper transaction isolation and row-level locking:
For production environments with concurrent users, we recommend using MySQL/MariaDB (InnoDB) or PostgreSQL.
Add the HasCredits trait to any model that should handle credits:
use Climactic\Credits\Traits\HasCredits;
class User extends Model
{
use HasCredits;
}// Add credits
$user->creditAdd(100.00, 'Subscription Activated');
// Deduct credits
$user->creditDeduct(50.00, 'Purchase Made');
// Get current balance
$balance = $user->creditBalance();
// Check if user has enough credits
if ($user->hasCredits(30.00)) {
// Proceed with transaction
}Transfer credits between two models:
$sender->creditTransfer($recipient, 100.00, 'Paying to user for their service');// Get last 10 transactions
$history = $user->creditHistory();
// Get last 20 transactions in ascending order
$history = $user->creditHistory(20, 'asc');Get balance as of a specific date:
$date = new DateTime('2023-01-01');
$balanceAsOf = $user->creditBalanceAt($date);Add additional information to transactions:
$metadata = [
'order_id' => 123,
'product' => 'Premium Subscription',
'user_id' => 456,
'tags' => ['premium', 'featured']
];
$user->creditAdd(100.00, 'Purchase', $metadata);The package provides powerful query scopes to filter transactions by metadata with built-in input validation for security.
Metadata keys must follow these rules:
'user.id', not 'user->id')" or ')// ✅ Valid
$user->credits()->whereMetadata('source', 'purchase')->get();
$user->credits()->whereMetadata('user.id', 123)->get();
$user->credits()->whereMetadata(' source ', 'test')->get(); // Trimmed automatically (not recommended)
// ❌ Invalid - will throw InvalidArgumentException
$user->credits()->whereMetadata('', 'value')->get(); // Empty key
$user->credits()->whereMetadata('data->key', 'value')->get(); // Arrow operator
$user->credits()->whereMetadata('data"key', 'value')->get(); // Contains quotes// Query by simple metadata value
$purchases = $user->credits()
->whereMetadata('source', 'purchase')
->get();
// Query with comparison operators
$highValue = $user->credits()
->whereMetadata('order_value', '>', 100)
->get();
// Query by nested metadata (using dot notation)
$specificUser = $user->credits()
->whereMetadata('user.id', 123)
->get();
// Deeply nested keys (use raw where for very deep nesting)
$results = $user->credits()
->where('metadata->data->level1->level2->value', 'found')
->get();// Check if metadata array contains a value
$premium = $user->credits()
->whereMetadataContains('tags', 'premium')
->get();
// Check if metadata key exists
$withOrderId = $user->credits()
->whereMetadataHas('order_id')
->get();
// Check if metadata key is null or doesn't exist
$withoutTags = $user->credits()
->whereMetadataNull('tags')
->get();
// Query by metadata array length
$multipleTags = $user->credits()
->whereMetadataLength('tags', '>', 1)
->get();$filtered = $user->credits()
->whereMetadata('source', 'purchase')
->whereMetadata('category', 'electronics')
->whereMetadataContains('tags', 'featured')
->where('amount', '>', 50)
->get();…Note: When using creditHistoryWithMetadata(), the filter array distinguishes between "two-parameter syntax" and "three-parameter syntax" by checking if the 'value' key exists:
'value' key exists: uses three-parameter form whereMetadata($key, $operator, $value)'value' key missing: uses two-parameter form whereMetadata($key, $operator) where operator becomes the valueThis allows proper handling of null values while maintaining shorthand syntax convenience.
For high-volume applications querying metadata frequently, consider adding database indexes. Without indexes, metadata queries perform full table scans. With proper indexes, queries become nearly instant even with millions of records.
Virtual generated columns extract JSON values into indexed columns for fast queries:
…Performance impact: Queries go from scanning millions of rows to using index lookups (1000x+ faster).
PostgreSQL's GIN (Generalized Inverted Index) provides efficient querying for all JSON operations:
…Note: The GIN index alone enables fast queries for all metadata keys. Path-specific indexes provide marginal additional performance.
SQLite has limited JSON indexing capabilities. For SQLite:
Index metadata keys that you query frequently:
// If you often query by source
$user->credits()->whereMetadata('source', 'purchase')->get();
// → Index: metadata_source
// If you filter by order_id
$user->credits()->whereMetadata('order_id', 12345)->get();
// → Index: metadata_order_id
// If you query by tags array
$user->credits()->whereMetadataContains('tags', 'premium')->get();
// → MySQL: Index on virtual column for tags
// → PostgreSQL: GIN index handles this automaticallyEXPLAIN to identify slow queriesEvents are fired for each credit transaction, transfer, and balance update.
The events are:
CreditsAddedCreditsDeductedCreditsTransferred| Method | Description |
|---|---|
creditAdd(float $amount, ?string $description = null, array $metadata = []) |
Add credits to the model |
creditDeduct(float $amount, ?string $description = null, array $metadata = []) |
Deduct credits from the model |
creditBalance() |
Get the current balance |
creditTransfer(Model $recipient, float $amount, ?string $description = null, array $metadata = []) |
Transfer credits to another model |
creditHistory(int $limit = 10, string $order = 'desc') |
Get transaction history |
hasCredits(float $amount) |
Check if model has enough credits |
creditBalanceAt(Carbon|DateTimeInterface|int $dateTime) |
Get balance at a specific time |
credits() |
Eloquent relationship to credit transactions |
| `creditsByMetadata(string $key, $operator, $value = null, int $li |
暂无开放 Issues,或尚未同步最近议题。