Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
L

laravel-credits

> 后端框架
Open source

A ledger-based Laravel package for managing credit-based systems in your application.

325 stars0 likes3 views
WebsiteGitHub

About

A ledger-based Laravel package for managing credit-based systems in your application.

Table of Contents

  • Laravel Credits
    • Table of Contents
    • Features
    • Sponsors
    • Installation
    • ⚙️ Configuration
      • ️ Database Recommendations
    • Usage
      • Setup Your Model
      • Basic Usage
      • Transfers
      • Transaction History
      • Historical Balance
      • Metadata
      • Querying by Metadata
        • Metadata Key Format
        • Basic Metadata Queries
        • Advanced Metadata Queries
        • Chaining Multiple Metadata Conditions
        • Convenience Methods
        • ⚡ Performance Optimization
          • When to Optimize
          • MySQL/MariaDB: Virtual Columns with Indexes
          • PostgreSQL: GIN Indexes on JSONB
          • SQLite: Limited Support
          • Choosing What to Index
          • Best Practices
      • Events
    • API Reference
      • Available Methods
      • Query Scopes
      • ⚠️ Deprecated Methods
    • Testing
    • Changelog
    • Contributing
    • Security Vulnerabilities
    • Support This Project
    • ⭐ Star History
    • License
    • ⚖️ Disclaimer

Features

  • Credit transactions
  • Credit transfers
  • Events for adding, deducting, and transferring credits
  • Balance tracking with running balance
  • Transaction history
  • Point-in-time balance lookup
  • Transaction metadata support
  • Powerful metadata querying with filters and scopes
  • ⚡ Efficient queries using running balance and indexes
  • Performance optimization guide for high-volume applications

Sponsors

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.

Installation

You can install the package via composer:

bash
composer require climactic/laravel-credits

Publish and run the migrations:

bash
php artisan vendor:publish --tag="credits-migrations"
php artisan migrate

Optionally publish the config file:

bash
php artisan vendor:publish --tag="credits-config"

⚙️ Configuration

php
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',
];

️ Database Recommendations

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:

  • ✅ MySQL/MariaDB: Requires InnoDB engine (default in modern versions)
  • ✅ PostgreSQL: Full support for row-level locking
  • ⚠️ SQLite: Row-level locking is ignored; concurrent operations may produce incorrect results in high-concurrency scenarios

For production environments with concurrent users, we recommend using MySQL/MariaDB (InnoDB) or PostgreSQL.

Usage

Setup Your Model

Add the HasCredits trait to any model that should handle credits:

php
use Climactic\Credits\Traits\HasCredits;

class User extends Model
{
    use HasCredits;
}

Basic Usage

php
// 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
}

Transfers

Transfer credits between two models:

php
$sender->creditTransfer($recipient, 100.00, 'Paying to user for their service');

Transaction History

php
// Get last 10 transactions
$history = $user->creditHistory();

// Get last 20 transactions in ascending order
$history = $user->creditHistory(20, 'asc');

Historical Balance

Get balance as of a specific date:

php
$date = new DateTime('2023-01-01');
$balanceAsOf = $user->creditBalanceAt($date);

Metadata

Add additional information to transactions:

php
$metadata = [
    'order_id' => 123,
    'product' => 'Premium Subscription',
    'user_id' => 456,
    'tags' => ['premium', 'featured']
];

$user->creditAdd(100.00, 'Purchase', $metadata);

Querying by Metadata

The package provides powerful query scopes to filter transactions by metadata with built-in input validation for security.

Metadata Key Format

Metadata keys must follow these rules:

  • Use dot notation for nested keys (e.g., 'user.id', not 'user->id')
  • Cannot be empty or contain only whitespace
  • Cannot contain quotes (" or ')
  • Whitespace is automatically trimmed
php
// ✅ 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

Basic Metadata Queries

php
// 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();

Advanced Metadata Queries

php
// 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();

Chaining Multiple Metadata Conditions

php
$filtered = $user->credits()
    ->whereMetadata('source', 'purchase')
    ->whereMetadata('category', 'electronics')
    ->whereMetadataContains('tags', 'featured')
    ->where('amount', '>', 50)
    ->get();

Convenience Methods

…

Note: When using creditHistoryWithMetadata(), the filter array distinguishes between "two-parameter syntax" and "three-parameter syntax" by checking if the 'value' key exists:

  • If 'value' key exists: uses three-parameter form whereMetadata($key, $operator, $value)
  • If 'value' key missing: uses two-parameter form whereMetadata($key, $operator) where operator becomes the value

This allows proper handling of null values while maintaining shorthand syntax convenience.

⚡ Performance Optimization

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.

When to Optimize
  • Small datasets ( 100k): Highly recommended for any metadata queries
MySQL/MariaDB: Virtual Columns with Indexes

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: GIN Indexes on JSONB

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: Limited Support

SQLite has limited JSON indexing capabilities. For SQLite:

  • Metadata queries work but will be slower on large datasets
  • Consider using a different database for production if metadata querying is critical
  • JSON1 extension must be enabled (available in SQLite 3.38+)
Choosing What to Index

Index metadata keys that you query frequently:

php
// 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 automatically
Best Practices
  1. Analyze your queries first: Use EXPLAIN to identify slow queries
  2. Index selectively: Only index frequently queried keys (each index adds storage overhead)
  3. Use composite indexes: For queries combining metadata with other columns
  4. Test with production data: Benchmark before and after indexing
  5. Monitor index usage: Remove unused indexes to save storage

Events

Events are fired for each credit transaction, transfer, and balance update.

The events are:

  • CreditsAdded
  • CreditsDeducted
  • CreditsTransferred

API Reference

Available Methods

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· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPcredit-management-systemhacktoberfestlaravellaravel-credits

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架