lukabuz/laravel-balance

(FORK OF vuer/laravel-balance) Laravel package that provide account balance and transactions functionality for Laravel

2.0.0 2023-04-30 02:44 UTC

This package is not auto-updated.

Last update: 2024-11-11 09:34:47 UTC


README

Latest Stable Version Total Downloads Latest Unstable Version License

Installation

You can install this package via composer using this command:

composer require lukabuz/laravel-balance

Next, you must install the service provider:

// config/app.php
'providers' => [
    ...
    Lukabuz\LaravelBalance\BalanceServiceProvider::class,
];

Publish migration and configuration file:

php artisan vendor:publish

After the migration has been published you can create the tables by running the migrations:

php artisan migrate

Usage

Preparing your model

Associate account balance with a model:

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Lukabuz\LaravelBalance\Models\AccountBalance;
use Lukabuz\LaravelBalance\Models\Interfaces\AccountBalanceHolderInterface

class User extends Model implements AccountBalanceHolderInterface
{
    public function accountBalances()
    {
        return $this->morphOne(AccountBalance::class, 'holder');
    }

    public function getAccount(string $currency): ?AccountBalance
    {
        return $this->accountBalances()->where('currency', $currency)->first();
    }

    public function addAccountBalance(AccountBalance $accountBalance)
    {
        $accountBalance->holder()->associate($this);
        $accountBalance->save();
    }
}

Account balance

Register dependencies:

<?php
use Lukabuz\LaravelBalance\Services\Accountant;
use Lukabuz\LaravelBalance\Services\TransactionProcessor;

class SomeController extends Controller
{
    /**
     * @var Accountant
     */
    private $accountant;
    
    /**
     * @var TransactionProcessor
     */
    private $transactionProcessor;

    public function __construct(Accountant $accountant, TransactionProcessor $transactionProcessor)
    {
        $this->accountant = $accountant;
        $this->transactionProcessor = $transactionProcessor;
    }
}

To create account use methods getAccountOrCreate or createAccount.

$account = $this->accountant->getAccountOrCreate($user, new \Money\Currency('EUR'));
$account = $this->accountant->createAccount($user, new \Money\Currency('EUR'));

To get existing account use method getAccount.

$account = $this->accountant->getAccount($user, new \Money\Currency('EUR'));

To get account balance values:

$currency = $account->getBalance()->getCurrency();
$amount = $account->getBalance()->getAmount();

Create transactions

To add 100 EUR to your balance:

$account = $this->accountant->getAccount($user, new \Money\Currency('EUR'));
$transaction = $this->transactionProcessor->create($account, new \Vuer\LaravelBalance\Dto\TransactionDto(100));

Only integers allowed, so then if you want to place decimals then consider storing 1 USD as 100.