编程

在 Eloquent 使用 Laravel Wallet 处理金钱交易

148 2024-04-12 02:13:00

Laravel Wallet 旨在提供可靠且灵活的交易,并处理在数据库中以精确计算的方式保存交易的复杂部分。它提供了直观的 API,易于使用和理解。

按照安装说明进行设置完,你可以在 User 模型中使用 HasBlance trait。

namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
use O21\LaravelWallet\Contracts\Payable;
use O21\LaravelWallet\Models\Concerns\HasBalance;
 
class User extends Model implements Payable
{
    use HasBalance;
}

以下是一些可以用来处理模型余额的可能命令。在以下示例中, $sender$receiver 通过 HasBalance trait 实现了 Payable 接口:

// Transfer money between sender and recipient
transfer(100, 'USD')->from($sender)->to($recipient)->commit();
 
// Deposit money into a recipient's account
deposit(100, 'USD')->to($recipient)->overcharge()->commit();
 
// Charge a user
charge(100, 'USD')->from($sender)->commit();

这个软件包是作者在项目中私下使用它的结果,经过改进,现在以开源形式发布。它包括余额精度的保障措施和旨在恢复修改的复杂回滚机制。

了解更多

更多详情请查看 GitHub 源码