### Install Laravel Wallet Swap Package (Bash) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/additions/swap.md Installs the bavix/laravel-wallet-swap package into your Laravel project using Composer. This command adds the package as a dependency and downloads it. ```bash composer req bavix/laravel-wallet-swap ``` -------------------------------- ### Publishing Laravel Wallet Migrations (Bash) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/introduction/installation.md Publishes the database migration files associated with the `laravel-wallet` package to the standard Laravel migrations directory. This command uses the `vendor:publish` Artisan command with a specific tag (`laravel-wallet-migrations`). Requires the package to be installed in a Laravel project. ```bash php artisan vendor:publish --tag=laravel-wallet-migrations ``` -------------------------------- ### Publishing Laravel Wallet Configuration (Bash) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/introduction/installation.md Publishes the configuration file for the `laravel-wallet` package to the `config/` directory. This command uses the `vendor:publish` Artisan command with the tag (`laravel-wallet-config`) and allows customization of the package's settings. Requires the package to be installed in a Laravel project. ```bash php artisan vendor:publish --tag=laravel-wallet-config ``` -------------------------------- ### Installing Laravel Wallet Package Composer (Bash) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/_include/composer.md This command uses the Composer package manager to require and install the bavix/laravel-wallet package as a dependency for the current project. It downloads the package and updates the composer.json and composer.lock files. ```bash composer req bavix/laravel-wallet ``` -------------------------------- ### Performing Float Deposit in Laravel PHP Source: https://github.com/bavix/laravel-wallet/blob/master/README.md This snippet demonstrates how to deposit fractional amounts into a wallet configured for float support. It shows the difference between the internal integer balance representation and the float representation accessible via `balanceFloat`. ```php $user = User::first(); $user->balance; // 100 $user->balanceFloat; // 1.00 $user->depositFloat(1.37); $user->balance; // 237 $user->balanceFloat; // 2.37 ``` -------------------------------- ### Retrieving Product Amount Before Failed SafePay - PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/purchases/commissions.md Shows how to retrieve an item instance and get its price for a customer before attempting a `safePay` transaction that is expected to fail due to insufficient funds. ```php $item = Item::first(); $item->getAmountProduct($user); // 100 ``` -------------------------------- ### Performing Product Purchases in Laravel PHP Source: https://github.com/bavix/laravel-wallet/blob/master/README.md This snippet demonstrates how a customer model can interact with a product model to perform purchases using the `pay` or `safePay` methods. It also shows how to check if an item has been paid for using `paid` and how to refund a purchase using `refund`. ```php $user = User::first(); $user->balance; // 100 $item = Item::first(); $user->pay($item); // If you do not have enough money, throw an exception var_dump($user->balance); // 0 if ($user->safePay($item)) { // try to buy again } var_dump((bool)$user->paid($item)); // bool(true) var_dump($user->refund($item)); // bool(true) var_dump((bool)$user->paid($item)); // bool(false) ``` -------------------------------- ### Publishing Updated Config File Bash Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/introduction/upgrade.md When upgrading to version 7.x.x, the `config/wallet.php` file underwent significant changes. Users who have published this file previously must re-publish it using the `vendor:publish` Artisan command with the `--force` flag to get the new structure. ```bash php artisan vendor:publish --tag=laravel-wallet-config --force ``` -------------------------------- ### Implementing Float Wallet in Laravel PHP Source: https://github.com/bavix/laravel-wallet/blob/master/README.md This snippet shows how to make a Laravel model compatible with fractional numbers for balances by adding the `HasWalletFloat` trait and implementing the `WalletFloat` interface, in addition to the basic `Wallet` interface. ```php use Bavix\Wallet\Traits\HasWalletFloat; use Bavix\Wallet\Interfaces\WalletFloat; use Bavix\Wallet\Interfaces\Wallet; class User extends Model implements Wallet, WalletFloat { use HasWalletFloat; } ``` -------------------------------- ### Performing Basic Wallet Transactions in Laravel PHP Source: https://github.com/bavix/laravel-wallet/blob/master/README.md This snippet demonstrates how to perform standard wallet operations like checking balance, depositing funds, withdrawing funds, and forcing a withdrawal (allowing negative balance). It uses the methods provided by the `HasWallet` trait. ```php $user = User::first(); $user->balanceInt; // 0 $user->deposit(10); $user->balance; // 10 $user->balanceInt; // int(10) $user->withdraw(1); $user->balance; // 9 $user->forceWithdraw(200, ['description' => 'payment of taxes']); $user->balance; // -191 ``` -------------------------------- ### Retrieving Item, Checking Product Amount and Balance in Laravel (PHP) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/purchases/payment-free.md This snippet shows how to fetch an item instance and access its price defined by the `getAmountProduct` method. It also shows that a product item model, even with the `HasWallet` trait, typically starts with a balance of 0. ```PHP $item = Item::first(); $item->getAmountProduct($user); // 100 $item->balance; // 0 ``` -------------------------------- ### Implementing Unlimited Product Interface in Laravel PHP Source: https://github.com/bavix/laravel-wallet/blob/master/README.md This snippet demonstrates how to define a Laravel model as a 'product' that can be purchased an unlimited number of times by adding the `HasWallet` trait and implementing the `ProductInterface`. It requires implementing `getAmountProduct` to define the price and `getMetaProduct` for transaction details. ```php use Bavix\Wallet\Traits\HasWallet; use Bavix\Wallet\Interfaces\Customer; use Bavix\Wallet\Interfaces\ProductInterface; class Item extends Model implements ProductInterface { use HasWallet; public function getAmountProduct(Customer $customer): int|string { return 100; } public function getMetaProduct(): ?array { return [ 'title' => $this->title, 'description' => 'Purchase of Product #' . $this->id, ]; } } ``` -------------------------------- ### Implementing Limited Product Interface in Laravel PHP Source: https://github.com/bavix/laravel-wallet/blob/master/README.md This snippet shows how to define a Laravel model as a 'product' with limited availability by adding the `HasWallet` trait and implementing the `ProductLimitedInterface`. In addition to price and meta data, it requires implementing `canBuy` to define purchase constraints. ```php use Bavix\Wallet\Traits\HasWallet; use Bavix\Wallet\Interfaces\Customer; use Bavix\Wallet\Interfaces\ProductLimitedInterface; class Item extends Model implements ProductLimitedInterface { use HasWallet; public function canBuy(Customer $customer, int $quantity = 1, bool $force = false): bool { /** * This is where you implement the constraint logic. * * If the service can be purchased once, then * return !$customer->paid($this); */ return true; } public function getAmountProduct(Customer $customer): int|string { return 100; } public function getMetaProduct(): ?array { return [ 'title' => $this->title, 'description' => 'Purchase of Product #' . $this->id, ]; } } ``` -------------------------------- ### Retrieving Product Amount Before Minimal Tax Payment - PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/purchases/commissions.md Shows how to retrieve an item model instance and get its price for a customer before a purchase transaction that might involve a minimal tax. ```php $item = Item::first(); $item->getAmountProduct($user); // 100 ``` -------------------------------- ### Setting Mathable Config to BrickMath PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/introduction/upgrade.md Following the removal of dynamic math class selection in version 6.0.x, the `mathable` configuration setting in `config/wallet.php` should be explicitly set to `BrickMath::class`, standardizing the math implementation. ```php 'mathable' => $mathClass, ``` ```php 'mathable' => BrickMath::class, ``` -------------------------------- ### Implementing Basic Wallet in Laravel PHP Source: https://github.com/bavix/laravel-wallet/blob/master/README.md This snippet shows how to make a Laravel model compatible with basic wallet functionality by adding the `HasWallet` trait and implementing the `Wallet` interface. This allows the model instance to hold a wallet and perform integer-based transactions. ```php use Bavix\Wallet\Traits\HasWallet; use Bavix\Wallet\Interfaces\Wallet; class User extends Model implements Wallet { use HasWallet; } ``` -------------------------------- ### Implementing Wallet Interface and Trait in Model PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/_include/models/user_simple.md This snippet shows how to modify a standard Laravel Eloquent model (`User` in this example) to make it compatible with the `Bavix\Wallet` package. It requires the model to implement the `Bavix\Wallet\Interfaces\Wallet` interface and use the `Bavix\Wallet\Traits\HasWallet` trait. This setup enables the model instance to hold and manage balances via the package's methods. ```php use Bavix\Wallet\Traits\HasWallet; use Bavix\Wallet\Interfaces\Wallet; class User extends Model implements Wallet { use HasWallet; } ``` -------------------------------- ### Implementing Customer Interface for Purchases in Laravel PHP Source: https://github.com/bavix/laravel-wallet/blob/master/README.md This snippet shows how to enable a Laravel model to act as a 'customer' capable of making purchases by adding the `CanPay` trait and implementing the `Customer` interface. This is required for using the package's purchase functionality. ```php use Bavix\Wallet\Traits\CanPay; use Bavix\Wallet\Interfaces\Customer; class User extends Model implements Customer { use CanPay; } ``` -------------------------------- ### Finding Item and Checking Initial Balance - PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/purchases/gift.md Retrieves an item model using Eloquent and checks its initial wallet balance. It also demonstrates calling the `getAmountProduct` method on the item to get its price for a specific customer context. ```PHP $item = Item::first(); $item->getAmountProduct($first); // 100 $item->balance; // 0 ``` -------------------------------- ### Eager Loading Wallets Relationship in Laravel PHP Source: https://github.com/bavix/laravel-wallet/blob/master/README.md This snippet shows how to eager load the `wallets` relationship when working with models configured to use the multi-wallet functionality provided by the package, preventing N+1 query issues for multiple wallets. ```php User::with('wallets'); ``` -------------------------------- ### Install Laravel Wallet UUID with Composer Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/additions/uuid.md This command uses Composer, the PHP dependency manager, to install the `bavix/laravel-wallet-uuid` package. This package adds UUID support to the Laravel Wallet library. It's the recommended method for adding this feature. ```bash composer req bavix/laravel-wallet-uuid ``` -------------------------------- ### Fetching Item, Getting Price, and Creating Receiving Wallet (PHP) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/purchases/receiving.md Retrieves the first Item model instance and calls `getAmountProduct` to get its price for the given user. It then uses the `createWallet` method (provided by wallet traits) to create a new, specific wallet on the item model intended for receiving payments, configured with a name and metadata. ```php $item = Item::first(); $item->getAmountProduct($user); // 100 $receiving = $item->createWallet([ 'name' => 'Dollar', 'meta' => [ 'currency' => 'USD', ], ]); ``` -------------------------------- ### Eager Loading Wallet Relationship in Laravel PHP Source: https://github.com/bavix/laravel-wallet/blob/master/README.md This snippet shows the standard way to eager load the default wallet relationship when working with models that have a single wallet associated, preventing N+1 query issues. ```php User::with('wallet'); ``` -------------------------------- ### Publishing Laravel Wallet Config (Bash) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/db/race-condition.md This command publishes the default configuration file for the bavix/laravel-wallet package to your application's config directory. This is a necessary first step to customize settings like the lock and cache drivers for handling race conditions. Requires a Laravel project with the package installed. ```bash php artisan vendor:publish --tag=laravel-wallet-config ``` -------------------------------- ### Removing Return Type Hints from Exchange Methods PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/introduction/upgrade.md Similar to product methods, version 5.0.x removed strong return type hints (`float`) from exchange rate processing service methods like `rate` and `convertTo` to support APM. ```php protected function rate(Wallet $wallet): float { ... } public function convertTo(Wallet $wallet): float { ... } ``` ```php protected function rate(Wallet $wallet) { ... } public function convertTo(Wallet $wallet) { ... } ``` -------------------------------- ### Calling Custom Method on Extended Wallet Model (PHP) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/introduction/configuration.md Shows an example of how to call a custom method, such as `helloWorld()`, on the extended wallet model instance. After registering the custom model in the configuration, you can access its methods directly via the relationship on the user model (`$user->wallet`). ```php echo $user->wallet->helloWorld(); ``` -------------------------------- ### Integrating HasWallet Trait and Wallet Interface (PHP) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/_include/eager_loading.md Defines a `User` model that implements the `Wallet` interface and uses the `HasWallet` trait. This integration enables the model to have a `wallet` relationship and access associated wallet methods provided by the bavix/laravel-wallet package. It requires the installation of the package. ```php use Bavix\Wallet\Traits\HasWallet; use Bavix\Wallet\Interfaces\Wallet; class User extends Model implements Wallet { use HasWallet; // public function wallet(): MorphOne... } ``` -------------------------------- ### Extending Base Wallet Model in Laravel Wallet (PHP) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/introduction/configuration.md Provides an example of extending the core `Bavix\Wallet\Models\Wallet` Eloquent model. This involves creating a new class, such as `MyWallet`, inheriting from `WalletBase` and adding custom methods or properties, like the `helloWorld` function shown. This allows for adding application-specific logic to wallet instances. ```php use Bavix\Wallet\Models\Wallet as WalletBase; class MyWallet extends WalletBase { public function helloWorld(): string { return "hello world"; } } ``` -------------------------------- ### Implementing User Model for Gifts - PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/purchases/gift.md To enable users to participate in gift transactions as customers, add the `CanPay` trait and implement the `Customer` interface to your User model. This setup allows the user to initiate payments and manage their wallet balance. ```PHP use Bavix\Wallet\Traits\CanPay; use Bavix\Wallet\Interfaces\Customer; class User extends Model implements Customer { use CanPay; } ``` -------------------------------- ### Removing Return Type Hints from Product Methods PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/introduction/upgrade.md To support Arbitrary Precision Mathematics (APM) in version 5.0.x, strong return type hints (`int`, `float`) were removed from product-related methods like `getAmountProduct`, `getFeePercent`, and `getMinimalFee` in the `Product` interface. ```php public function getAmountProduct(Customer $customer): int { ... } public function getFeePercent(): float { ... } public function getMinimalFee(): int { ... } ``` ```php public function getAmountProduct(Customer $customer) { ... } public function getFeePercent() { ... } public function getMinimalFee() { ... } ``` -------------------------------- ### Setting Up Model for Transaction Confirmation (PHP) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/single/confirm.md This snippet shows how to modify a Laravel model (e.g., User) to make it capable of confirming transactions. It requires adding the `HasWallet` and `CanConfirm` traits and implementing the `Wallet` and `Confirmable` interfaces from the `bavix/laravel-wallet` package. This setup allows the model instance to hold a wallet and confirm unconfirmed transactions. ```php use Bavix\Wallet\Interfaces\Confirmable; use Bavix\Wallet\Interfaces\Wallet; use Bavix\Wallet\Traits\CanConfirm; use Bavix\Wallet\Traits\HasWallet; class UserConfirm extends Model implements Wallet, Confirmable { use HasWallet, CanConfirm; } ``` -------------------------------- ### Checking Wallet Balances Before Force Transfer - PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/multi/transfer.md Displays the current balances of the two wallets just before initiating a force transfer operation. This helps verify the starting state for the subsequent example where the balance is insufficient for a standard transfer. ```php $firstWallet->balance; // 100 $lastWallet->balance; // 0 ``` -------------------------------- ### Fixing Transfer Structure with Artisan Command Bash Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/introduction/upgrade.md To migrate the transfer structure in the database for UUID support in version 9.0.x, a new Artisan command `bx:transfer:fix` must be run. This command should be executed repeatedly until it completes immediately, indicating all incorrect transfer entries have been fixed. ```bash artisan bx:transfer:fix ``` -------------------------------- ### Implementing getUniqueId Method in Product PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/introduction/upgrade.md As of version 3.0.x, the `Product` interface requires a new method `getUniqueId` which must return a unique string identifier for the product. This snippet provides an example implementation returning the model's primary key as a string. ```php class Item extends Model implements Product { // Your method public function getUniqueId(): string { return (string)$this->getKey(); } } ``` -------------------------------- ### Comparing Transaction Counts PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/multi/transaction-filter.md This example illustrates the difference between the `transactions()` method (returning all owner transactions) and the `walletTransactions()` method (returning transactions for a specific wallet) by performing various deposit/withdraw actions and comparing the counts. It demonstrates how `transactions()` aggregates across all wallets owned by the user, while `walletTransactions()` is specific to the wallet instance it's called on. ```php $user->transactions()->count(); // 0 // Multi wallets and default wallet can be used together // default wallet $user->deposit(100); $user->wallet->deposit(200); $user->wallet->withdraw(1); // usd $usd = $user->createWallet(['name' => 'USD']); $usd->deposit(100); // eur $eur = $user->createWallet(['name' => 'EUR']); $eur->deposit(100); $user->transactions()->count(); // 5 $user->wallet->transactions()->count(); // 5 $usd->transactions()->count(); // 5 $eur->transactions()->count(); // 5 // the transactions method returns data relative to the owner of the wallet, for all transactions $user->walletTransactions()->count(); // 3. we get the default wallet $user->wallet->walletTransactions()->count(); // 3 $usd->walletTransactions()->count(); // 1 $eur->walletTransactions()->count(); // 1 ``` -------------------------------- ### Implementing ProductInterface for Unlimited Stock Item Model in Laravel (PHP) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/purchases/payment-free.md This code demonstrates how to prepare an Item model to act as a purchasable product with unlimited stock using the `HasWallet` trait and implementing the `ProductInterface`. It requires defining methods like `getAmountProduct` for the price and `getMetaProduct` for transaction metadata. ```PHP use Bavix\Wallet\Traits\HasWallet; use Bavix\Wallet\Interfaces\Customer; use Bavix\Wallet\Interfaces\ProductInterface; class Item extends Model implements ProductInterface { use HasWallet; public function getAmountProduct(Customer $customer): int|string { return 100; } public function getMetaProduct(): ?array { return [ 'title' => $this->title, 'description' => 'Purchase of Product #' . $this->id, ]; } } ``` -------------------------------- ### Creating and Confirming Unconfirmed Deposit (PHP) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/single/confirm.md This example shows how to perform a deposit transaction without immediate confirmation using the `deposit` method with the third parameter set to `false`. It then demonstrates how to confirm the previously created unconfirmed transaction using the `confirm` method on the same model instance that initiated the transaction. Confirming the transaction updates the wallet balance. ```php $user->balance; // 0 $transaction = $user->deposit(100, null, false); // not confirm $transaction->confirmed; // bool(false) $user->balance; // 0 $user->confirm($transaction); // bool(true) $transaction->confirmed; // bool(true) $user->balance; // 100 ``` -------------------------------- ### Retrieving User Model Instance (PHP) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/multi/new-wallet.md Fetches the first user record from the database using Laravel's Eloquent ORM. This user instance will be used to demonstrate wallet creation and interaction with the `bavix/laravel-wallet` package. ```php $user = User::first(); ``` -------------------------------- ### Creating and Depositing to a Specific Wallet (PHP) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/multi/new-wallet.md Demonstrates creating a wallet with a unique slug for a user, checking its existence before and after creation, and performing a deposit operation. It shows how to access the wallet's balance. Requires a user model with the `HasWallets` trait. ```php $user->hasWallet('my-wallet'); // bool(false) $wallet = $user->createWallet([ 'name' => 'New Wallet', 'slug' => 'my-wallet', ]); $user->hasWallet('my-wallet'); // bool(true) $wallet->deposit(100); $wallet->balance; // 100 $wallet->balanceFloatNum; // 1.00 ``` -------------------------------- ### Implementing ProductLimitedInterface for Limited Stock Item Model in Laravel (PHP) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/purchases/payment-free.md This snippet illustrates how to set up an Item model as a product with limited stock by using the `HasWallet` trait and implementing `ProductLimitedInterface`. It requires implementing `canBuy` for availability checks, `getAmountProduct` for price, and `getMetaProduct` for metadata. The `canBuy` method is where custom purchase constraints are implemented. ```PHP use Bavix\Wallet\Traits\HasWallet; use Bavix\Wallet\Interfaces\Customer; use Bavix\Wallet\Interfaces\ProductLimitedInterface; class Item extends Model implements ProductLimitedInterface { use HasWallet; public function canBuy(Customer $customer, int $quantity = 1, bool $force = false): bool { /** * This is where you implement the constraint logic. * * If the service can be purchased once, then * return !$customer->paid($this); */ return true; } public function getAmountProduct(Customer $customer): int|string { return 100; } public function getMetaProduct(): ?array { return [ 'title' => $this->title, 'description' => 'Purchase of Product #' . $this->id, ]; } } ``` -------------------------------- ### Executing Purchase and Refund Operations PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/introduction/basic-usage.md Demonstrates the process of purchasing an item using the `pay` (throws exception on failure) or `safePay` (returns boolean) methods on the customer model. Also shows how to check payment status with `paid` and initiate a refund with `refund`, illustrating the state changes. ```php $user = User::first(); $user->balance; // 100 $item = Item::first(); $user->pay($item); // If you do not have enough money, throw an exception var_dump($user->balance); // 0 if ($user->safePay($item)) { // try to buy again ) } var_dump((bool)$user->paid($item)); // bool(true) var_dump($user->refund($item)); // bool(true) var_dump((bool)$user->paid($item)); // bool(false) ``` -------------------------------- ### Exchange Funds Between Wallets (PHP) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/additions/swap.md Demonstrates retrieving specific wallets by slug ('rub' and 'usd') for a user and performing an exchange transaction. It shows accessing balances before and after exchanging 10 units from the 'usd' wallet to the 'rub' wallet. ```php $rub = $user->getWallet('rub'); $usd = $user->getWallet('usd'); $usd->balance; // 200 $rub->balance; // 0 $usd->exchange($rub, 10); $usd->balance; // 190 $rub->balance; // 622 ``` -------------------------------- ### Performing Free Payment and Verifying Status in Laravel (PHP) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/purchases/payment-free.md This crucial snippet shows how to execute a 'free' payment transaction using the `payFree` method, where the user acquires the item without their balance being affected. It then demonstrates verifying the transaction status using `paid` and checking the balances again to confirm no change. ```PHP $user->payFree($item); (bool)$user->paid($item); // bool(true) $user->balance; // 100 $item->balance; // 0 ``` -------------------------------- ### Process Shopping Cart Payment - PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/purchases/cart.md This comprehensive snippet demonstrates the full workflow for filling and paying for a shopping cart. It involves fetching items, initializing a Cart object, adding items with quantities, calculating the total, depositing funds into the user's wallet, and finally executing the `payCart` method. ```php use Bavix\Wallet\Objects\Cart; $user = User::first(); $user->balance; // 0 $list = [ 'potato' => 3, 'carrot' => 10, ]; $products = Item::query() ->whereIn('slug', ['potato', 'carrot']) ->get(); $cart = app(Cart::class); foreach ($products as $product) { $cart = $cart->withItem($product, quantity: $list[$product->slug]); } $cartTotal = $cart->getTotal($user); // 15127 $user->deposit($cartTotal); $user->balanceInt; // 15127 $user->balanceFloat; // 151.27 $cart = $cart->withItem(current($products), pricePerItem: 500); // 15127+500 $user->deposit(500); $user->balanceInt; // 15627 $user->balanceFloat; // 156.27 (bool)$user->payCart($cart); // true $user->balanceFloat; // 0 ``` -------------------------------- ### Create Multiple User Wallets (PHP) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/additions/swap.md Creates two distinct wallets ('usd' and 'rub') for a user instance. Each wallet is configured with a name, a unique slug for retrieval, and metadata including currency information. ```php $usd = $user->createWallet([ 'name' => 'My Dollars', 'slug' => 'usd', 'meta' => ['currency' => 'USD'], ]); $rub = $user->createWallet([ 'name' => 'My Ruble', 'slug' => 'rub', 'meta' => ['currency' => 'RUB'], ]); ``` -------------------------------- ### Configuring Limited Product Item Model PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/purchases/refund.md Configures an Item model as a product with limited stock for the wallet system. It uses `HasWallet` and implements `ProductLimitedInterface`, requiring `canBuy`, `getAmountProduct`, and `getMetaProduct` methods. Requires `Bavix\Wallet\Traits\HasWallet`, `Bavix\Wallet\Interfaces\Customer`, and `Bavix\Wallet\Interfaces\ProductLimitedInterface`. ```php use Bavix\Wallet\Traits\HasWallet; use Bavix\Wallet\Interfaces\Customer; use Bavix\Wallet\Interfaces\ProductLimitedInterface; class Item extends Model implements ProductLimitedInterface { use HasWallet; public function canBuy(Customer $customer, int $quantity = 1, bool $force = false): bool { /** * This is where you implement the constraint logic. * * If the service can be purchased once, then * return !$customer->paid($this); */ return true; } public function getAmountProduct(Customer $customer): int|string { return 100; } public function getMetaProduct(): ?array { return [ 'title' => $this->title, 'description' => 'Purchase of Product #' . $this->id, ]; } } ``` -------------------------------- ### Adding Customer Parameter to getAmountProduct PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/introduction/upgrade.md In version 4.0.x, the `getAmountProduct` method on models representing products must accept a `Customer` object as an argument. This allows product price calculation logic to potentially depend on the customer making the purchase. ```php public function getAmountProduct(): int { return $this->price; } ``` ```php public function getAmountProduct(Customer $customer): int { return $this->price; } ``` -------------------------------- ### Implementing Minimal Taxable Product Model - PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/purchases/commissions.md Configures the Item model as a purchasable product with a minimum fixed commission fee. This requires adding the `HasWallet` trait and implementing the `ProductInterface` and `MinimalTaxable` interfaces, including methods for amount, metadata, percentage fee, and the minimal fee value. ```php use Bavix\Wallet\Traits\HasWallet; use Bavix\Wallet\Interfaces\Customer; use Bavix\Wallet\Interfaces\MinimalTaxable; use Bavix\Wallet\Interfaces\ProductInterface; class Item extends Model implements ProductInterface, MinimalTaxable { use HasWallet; public function getAmountProduct(Customer $customer): int|string { return 100; } public function getMetaProduct(): ?array { return [ 'title' => $this->title, 'description' => 'Purchase of Product #' . $this->id, ]; } public function getFeePercent() { return 0.03; // 3% } public function getMinimalFee() { return 5; // 3%, minimum 5 } } ``` -------------------------------- ### Configuring Unlimited Product Item Model PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/purchases/refund.md Configures an Item model to function as a product with unlimited stock in the wallet system. It uses the `HasWallet` trait and implements `ProductInterface`, requiring the `getAmountProduct` and `getMetaProduct` methods. Requires `Bavix\Wallet\Traits\HasWallet`, `Bavix\Wallet\Interfaces\Customer`, and `Bavix\Wallet\Interfaces\ProductInterface`. ```php use Bavix\Wallet\Traits\HasWallet; use Bavix\Wallet\Interfaces\Customer; use Bavix\Wallet\Interfaces\ProductInterface; class Item extends Model implements ProductInterface { use HasWallet; public function getAmountProduct(Customer $customer): int|string { return 100; } public function getMetaProduct(): ?array { return [ 'title' => $this->title, 'description' => 'Purchase of Product #' . $this->id, ]; } } ``` -------------------------------- ### Retrieving Product Amount Before Purchase - PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/purchases/commissions.md Shows how to retrieve an item model instance and determine its price (amount) for a given customer using the `getAmountProduct` method. ```php $item = Item::first(); $item->getAmountProduct($user); // 100 ``` -------------------------------- ### Configuring Item Model as Unlimited Product PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/introduction/basic-usage.md Sets up an Item model to represent a product that can be purchased multiple times. It adds the `HasWallet` trait, implements `ProductInterface`, and defines the required methods to return the product price (`getAmountProduct`) and optional purchase details (`getMetaProduct`). ```php use Bavix\Wallet\Traits\HasWallet; use Bavix\Wallet\Interfaces\Customer; use Bavix\Wallet\Interfaces\ProductInterface; class Item extends Model implements ProductInterface { use HasWallet; public function getAmountProduct(Customer $customer): int|string { return 100; } public function getMetaProduct(): ?array { return [ 'title' => $this->title, 'description' => 'Purchase of Product #' . $this->id, ]; } } ``` -------------------------------- ### Retrieving User and Checking Balance in Laravel (PHP) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/purchases/payment-free.md This code demonstrates how to retrieve a user instance from the database and check their current wallet balance using the `balance` property. This is typically done after applying the `HasWallet` or `CanPay` trait to the user model. ```PHP $user = User::first(); $user->balance; // 100 ``` -------------------------------- ### Combining Default and Multi-Wallet Traits (PHP) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/multi/new-wallet.md Shows how to include both the `HasWallet` trait (for the default wallet) and the `HasWallets` trait (for multiple specific wallets) in the User model. This allows the user to have both a default wallet and additional named wallets simultaneously using the `bavix/laravel-wallet` package. ```php use Bavix\Wallet\Traits\HasWallet; use Bavix\Wallet\Traits\HasWallets; use Bavix\Wallet\Interfaces\Wallet; class User extends Model implements Wallet { use HasWallet, HasWallets; } ``` -------------------------------- ### Performing Basic Wallet Transactions PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/introduction/basic-usage.md Demonstrates how to use the `deposit`, `withdraw`, and `forceWithdraw` methods on a model enabled with the `HasWallet` trait. Shows how the balance changes after each operation, including achieving negative balances with `forceWithdraw`. ```php $user = User::first(); $user->balance; // 0 $user->deposit(10); $user->balance; // 10 $user->withdraw(1); $user->balance; // 9 $user->forceWithdraw(200, ['description' => 'payment of taxes']); $user->balance; // -191 ``` -------------------------------- ### Updating canBuy Method Signature PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/introduction/upgrade.md Version 3.0.x introduced a new `$quantity` parameter to the `canBuy` method in the `Product` interface. This change requires implementers of the interface to update their method signature to include the new integer parameter with a default value of 1. ```php // old public function canBuy(Customer $customer, bool $force = false): bool ``` ```php // new public function canBuy(Customer $customer, int $quantity = 1, bool $force = false): bool ``` -------------------------------- ### Finding Distinct Laravel User Models - PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/multi/transfer.md Shows how to fetch the first and last user records from the database using Laravel's Eloquent ORM, ensuring they are different users based on their primary key. These users will serve as the holders of the wallets for the transfer example. ```php $first = User::first(); $last = User::orderBy('id', 'desc')->first(); // last user $first->getKey() !== $last->getKey(); // true ``` -------------------------------- ### Integrating Laravel Wallet Traits to User Model - PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/cqrs/create-wallet.md This snippet shows how to add the necessary traits (`HasWallet`, `HasWallets`) and implement the `Wallet` interface on a Laravel User model. This integration enables the User model to utilize the wallet functionalities provided by the bavix/laravel-wallet package. ```php use Bavix\Wallet\Traits\HasWallet; use Bavix\Wallet\Traits\HasWallets; use Bavix\Wallet\Interfaces\Wallet; class User extends Model implements Wallet { use HasWallet, HasWallets; } ``` -------------------------------- ### Implementing Item Model for Limited Products - PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/purchases/gift.md For items with a limited supply, add the `HasWallet` trait and implement the `ProductLimitedInterface`. This requires implementing `canBuy` to define availability logic, along with `getAmountProduct` and `getMetaProduct` for price and metadata. ```PHP use Bavix\Wallet\Traits\HasWallet; use Bavix\Wallet\Interfaces\Customer; use Bavix\Wallet\Interfaces\ProductLimitedInterface; class Item extends Model implements ProductLimitedInterface { use HasWallet; public function canBuy(Customer $customer, int $quantity = 1, bool $force = false): bool { /** * This is where you implement the constraint logic. * * If the service can be purchased once, then * return !$customer->paid($this); */ return true; } public function getAmountProduct(Customer $customer): int|string { return 100; } public function getMetaProduct(): ?array { return [ 'title' => $this->title, 'description' => 'Purchase of Product #' . $this->id, ]; } } ``` -------------------------------- ### Updating Cart DTO Usage PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/introduction/upgrade.md Version 8.1.x introduced fluent Data Transfer Objects (DTOs) for the Cart functionality. Old methods like `addItem` and `setMeta` are replaced by fluent `withItem` and `withMeta` methods, supporting method chaining for building the cart object. ```php // old $cart = app(\Bavix\Wallet\Objects\Cart::class) ->addItems($products) ->addItem($product) ->setMeta(['hello' => 'world']); $cart->addItem($product); ``` ```php // new. fluent $cart = app(\Bavix\Wallet\Objects\Cart::class) ->withItems($products) ->withItem($product) ->withMeta(['hello' => 'world']); $cart = $cart->withItem($product); ``` -------------------------------- ### Integrating ProductInterface - Item Model PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/purchases/payment.md Set up an item model to be purchasable by adding the `HasWallet` trait and implementing the `ProductInterface` for unlimited quantities. This requires implementing methods like `getAmountProduct` to define the price and `getMetaProduct` for transaction metadata. ```php use Bavix\Wallet\Traits\HasWallet; use Bavix\Wallet\Interfaces\Customer; use Bavix\Wallet\Interfaces\ProductInterface; class Item extends Model implements ProductInterface { use HasWallet; public function getAmountProduct(Customer $customer): int|string { return 100; } public function getMetaProduct(): ?array { return [ 'title' => $this->title, 'description' => 'Purchase of Product #' . $this->id, ]; } } ``` -------------------------------- ### Removing Math Class Detection Logic PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/introduction/upgrade.md In version 6.0.x, the library standardizes on the `brick/math` library for precision mathematics. The logic that previously detected and selected math classes based on available PHP extensions (`bcmath`, `BigDecimal`) is no longer necessary and should be removed from the `config/wallet.php` file. ```php $bcLoaded = extension_loaded('bcmath'); $mathClass = Math::class; switch (true) { case class_exists(BigDecimal::class): $mathClass = BrickMath::class; break; case $bcLoaded: $mathClass = BCMath::class; break; } ``` -------------------------------- ### Implementing Taxable Product Model with HasWallet - PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/purchases/commissions.md Define your Item model as a purchasable product subject to a percentage-based commission. This requires adding the `HasWallet` trait and implementing the `ProductLimitedInterface` and `Taxable` interfaces, including methods for purchase eligibility, product amount, metadata, and commission percentage calculation. ```php use Bavix\Wallet\Traits\HasWallet; use Bavix\Wallet\Interfaces\Customer; use Bavix\Wallet\Interfaces\Taxable; use Bavix\Wallet\Interfaces\ProductLimitedInterface; class Item extends Model implements ProductLimitedInterface, Taxable { use HasWallet; public function canBuy(Customer $customer, int $quantity = 1, bool $force = false): bool { /** * If the service can be purchased once, then * return !$customer->paid($this); */ return true; } public function getAmountProduct(Customer $customer): int|string { return 100; } public function getMetaProduct(): ?array { return [ 'title' => $this->title, 'description' => 'Purchase of Product #' . $this->id, ]; } public function getFeePercent() { return 0.03; // 3% } } ``` -------------------------------- ### Initializing Wallet Transaction Query PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/multi/transaction-filter.md This snippet shows how to get a query builder instance for transactions specifically associated with a single `Wallet` model using the `walletTransactions` method. It requires a valid `Wallet` object. The method returns a database query builder instance allowing further filtering and operations. ```php /** @var \Bavix\Wallet\Models\Wallet $wallet */ $query = $wallet->walletTransactions(); ``` -------------------------------- ### Initiating Transfer with Custom Options using Laravel Wallet PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/single/transfer.md Demonstrates how to perform a transfer between two users using the `transfer` method, including passing an `Extra` object to provide custom data for the deposit and withdraw operations, and controlling the confirmation status of the withdraw. Requires users to have the `HasWallet` trait. Inputs are the recipient user object, amount, and an optional `Extra` object. Output is likely a `Transfer` object. ```php $transfer = $user1->transfer( $user2, 511, new Extra( deposit: [ 'type' => 'extra-deposit', ], withdraw: new Option( [ 'type' => 'extra-withdraw', ], false // confirmed ), extra: [ 'msg' => 'hello world', ], ) ); ``` -------------------------------- ### Retrieving First and Last Users (PHP) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/fractional/transfer.md Uses Eloquent ORM methods `first()` and `orderBy('id', 'desc')->first()` to retrieve the first and last user records from the database. These user objects (`$first`, `$last`) are used as recipients/senders in subsequent transfer examples. It also asserts that the retrieved users are distinct. ```php $first = User::first(); $last = User::orderBy('id', 'desc')->first(); // last user $first->getKey() !== $last->getKey(); // true ``` -------------------------------- ### Changing Service Container Binding PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/introduction/upgrade.md In version 3.0.x, the service container bindings for models were updated to use class names directly instead of string paths. This snippet shows the change from using the string path `bavix.wallet::transaction` to the class reference `Bavix\Wallet\Models\Transaction::class` when resolving the transaction model. ```php // old app('bavix.wallet::transaction'); ``` ```php // new app(Bavix\Wallet\Models\Transaction::class); ``` -------------------------------- ### Checking User Float Balance Before Force Transfer (PHP) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/fractional/transfer.md Accesses the `balanceFloatNum` property on user objects (`$first`, `$last`) to display their current float balances before a forced transfer operation is initiated. This shows the starting state of the balances before demonstrating the force transfer functionality. Requires users to use the `HasWalletFloat` trait. ```php $first->balanceFloatNum; // 100 $last->balanceFloatNum; // 0 ``` -------------------------------- ### Performing Batch Deposits with New API - PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/high-performance/batch-transactions.md Demonstrates the recommended, highly efficient method for performing batch deposits using the `TransactionQueryHandlerInterface::apply` method. It processes an array of `TransactionQuery::createDeposit` objects in a single batch operation, significantly reducing database query overhead. Requires the `bavix/laravel-wallet` package and the new API handlers. ```php use Bavix\Wallet\External\Api\TransactionQuery; use Bavix\Wallet\External\Api\TransactionQueryHandlerInterface; app(TransactionQueryHandlerInterface::class)->apply( array_map( static fn (Wallet $wallet) => TransactionQuery::createDeposit($wallet, $amount, null), $wallets ) ); ``` -------------------------------- ### Configuring Item Model as Limited Product PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/introduction/basic-usage.md Configures an Item model as a product with purchase limitations. It uses the `ProductLimitedInterface`, adds the `HasWallet` trait, and requires implementing the `canBuy` method for custom purchase logic, in addition to `getAmountProduct` and `getMetaProduct`. ```php use Bavix\Wallet\Traits\HasWallet; use Bavix\Wallet\Interfaces\Customer; use Bavix\Wallet\Interfaces\ProductLimitedInterface; class Item extends Model implements ProductLimitedInterface { use HasWallet; public function canBuy(Customer $customer, int $quantity = 1, bool $force = false): bool { /** * This is where you implement the constraint logic. * * If the service can be purchased once, then * return !$customer->paid($this); */ return true; } public function getAmountProduct(Customer $customer): int|string { return 100; } public function getMetaProduct(): ?array { return [ 'title' => $this->title, 'description' => 'Purchase of Product #' . $this->id, ]; } } ``` -------------------------------- ### Retrieving User Balance Before Purchase - PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/purchases/commissions.md Demonstrates how to fetch a user model instance and check their current wallet balance before initiating a purchase transaction. ```php $user = User::first(); $user->balance; // 103 ``` -------------------------------- ### Define Wallet-Enabled User Model (PHP) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/additions/swap.md Configures a Laravel User model to support both a default wallet and multiple named wallets using the HasWallet and HasWallets traits from the Laravel Wallet package. The model must also implement the Wallet interface. ```php use Bavix\Wallet\Interfaces\Wallet; use Bavix\Wallet\Traits\HasWallets; use Bavix\Wallet\Traits\HasWallet; class User extends Model implements Wallet { use HasWallet, HasWallets; } ``` -------------------------------- ### Cancelling Confirmed Transaction in Laravel Wallet (PHP) Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/single/cancel.md This example shows the practical steps to cancel a confirmed transaction. It first creates a deposit transaction, checks its confirmation status and the user's balance, then calls the `resetConfirm` method on the user model with the transaction object to cancel it, demonstrating that the transaction becomes unconfirmed and the balance is reversed. ```php $user->balance; // 0 $transaction = $user->deposit(100); // confirmed transaction $transaction->confirmed; // bool(true) $user->balance; // 100 $user->resetConfirm($transaction); // bool(true) $transaction->confirmed; // bool(false) $user->balance; // 0 ``` -------------------------------- ### Finding a User - PHP Source: https://github.com/bavix/laravel-wallet/blob/master/docs/guide/single/withdraw.md This snippet demonstrates how to retrieve a user instance from the database. The user is assumed to have the `HasWallet` trait applied to enable wallet functionality. ```php $user = User::first(); ```