geowrgetudor/laravel-balance

A credit system / balance for Laravel.

0.2.3 2024-10-15 20:51 UTC

This package is auto-updated.

Last update: 2024-11-15 20:58:29 UTC


README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

This is a small package that adds a credit system that you might need for various reasons:

  • awarding users based on their activity
  • rewards in credits instead of real money
  • rewards in credits for referrals
  • etc.

Installation

Install the package via composer:

composer require geowrgetudor/laravel-balance

Publish and run the migrations with:

php artisan vendor:publish --tag="balance-migrations"
php artisan migrate

If you decide to change the default migration table name, make sure you publish the config file and change the table name there too:

php artisan vendor:publish --tag="balance-config"

This is the contents of the published config file:

return [
    /**
     * Default table name.
     * If you have changed the migration, make sure you change this too.
     */
    'table' => 'balances',
    'default_currency' => 'EUR', // Default Currency
];

Prepare your model

Add the HasBalance trait to any model you need to.

use Geow\Balance\Traits\HasBalance;

class User extends Model {
    // ...
    use HasBalance;

}

Usage

// Set balance (similar to increaseCredit() method - just a naming difference)
$user->setCredit(2000);

// Get balance
$user->credit;

// Increase balance
$user->increaseCredit(1000);

// Decrease balance
$user->decreaseCredit(500);

// Reset balance to 0
$user->resetCredit();

// Check if the user has balance
$user->hasCredit();

// Passing a reason for setting/increasing/deacreasing the balance
$user->setCredit(20000, 'Signup bonus');
$user->increaseCredit(1000, 'Awarded credits');
$user->decreaseCredit(250, 'Service usage');

// Get balance as currency
$user->increaseCredit(1000);
$user->credit; // returns 1000 (represeting cents)
$user->creditCurrency; // returns $10.00 (representing dollars)

// If you need to display using a different currency
$user->withCurrency('EUR')->creditCurrency // returns €10.00

// Getting all model related transactions (increases and decresed in balance)
$user->credits; // Returns \Illuminate\Database\Eloquent\Collection

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.