Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Wallet Laravel Package

zotel/laravel-wallet

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require zotel-laravel-wallet
    

    Publish the config and migrations:

    php artisan vendor:publish --provider="Zotel\Wallet\WalletServiceProvider"
    php artisan migrate
    
  2. First Use Case: Create a wallet for a user (e.g., User model):

    use Zotel\Wallet\Models\Wallet;
    
    // Create a wallet for a user
    $user = User::find(1);
    $wallet = Wallet::create([
        'user_id' => $user->id,
        'balance' => 1000.00,
        'currency' => 'USD',
    ]);
    
  3. Key Files to Review:

    • config/wallet.php (default settings, currencies, etc.)
    • app/Models/Wallet.php (customize if needed)
    • routes/wallet.php (API endpoints if using web routes)

Implementation Patterns

Core Workflows

  1. Wallet Creation & Management:

    • Attach wallets to users/models via user_id or custom foreign keys.
    • Use Wallet::create() or user->wallet()->create() (if using relationships).
    • Example with relationship:
      // In User model:
      public function wallet() {
          return $this->hasOne(Wallet::class);
      }
      
      // Usage:
      $user->wallet()->create(['balance' => 500.00]);
      
  2. Transactions:

    • Deposit:
      $wallet->deposit(100.00, 'Payment received', 'invoice_123');
      
    • Withdrawal:
      $wallet->withdraw(50.00, 'Product purchase', 'order_456');
      
    • Transfer (between wallets):
      $wallet->transfer($targetWallet, 75.00, 'Gift to friend');
      
  3. Events & Observers:

    • Listen for wallet.created, wallet.deposited, wallet.withdrawn, etc.
    • Example observer:
      use Zotel\Wallet\Events\WalletDeposited;
      
      WalletDeposited::dispatch($wallet, $amount, $description);
      
  4. API Integration:

    • Use the built-in API routes (routes/wallet.php) or create custom controllers.
    • Example endpoint for balance check:
      Route::get('/wallet/balance', function (Wallet $wallet) {
          return response()->json(['balance' => $wallet->balance]);
      });
      
  5. Multi-Currency Support:

    • Configure supported currencies in config/wallet.php.
    • Convert balances dynamically:
      $wallet->convert('EUR'); // Returns converted balance
      

Advanced Patterns

  1. Custom Validation:

    • Extend the Wallet model to add validation rules:
      protected $rules = [
          'balance' => 'required|numeric|min:0',
          'currency' => 'required|in:USD,EUR,GBP',
      ];
      
  2. Webhooks:

    • Trigger external services on wallet events (e.g., Stripe, PayPal):
      event(new \Zotel\Wallet\Events\WalletDeposited($wallet, $amount));
      
  3. Batch Operations:

    • Process multiple transactions in a single query:
      $wallet->batchTransactions([
          ['type' => 'deposit', 'amount' => 100.00, 'description' => 'Batch deposit'],
          ['type' => 'withdraw', 'amount' => 20.00, 'description' => 'Batch withdrawal'],
      ]);
      
  4. Testing:

    • Use the WalletFactory for seed data:
      $wallet = Wallet::factory()->create(['balance' => 1000.00]);
      
    • Mock transactions in unit tests:
      $this->partialMock(Wallet::class, 'deposit')
           ->expects('deposit')
           ->with(100.00, 'Test', 'test_123');
      

Gotchas and Tips

Common Pitfalls

  1. Floating-Point Precision:

    • Use bcmath or gmp for financial calculations to avoid rounding errors:
      $amount = bcadd($wallet->balance, '100.50', 2);
      
  2. Race Conditions:

    • Always use database transactions for critical operations:
      DB::transaction(function () use ($wallet) {
          $wallet->withdraw(50.00, 'Safe purchase');
      });
      
  3. Currency Mismatches:

    • Ensure all transactions use the wallet’s configured currency. Cross-currency operations require explicit conversion.
  4. Observer Conflicts:

    • If using Laravel’s built-in observers, disable them for the Wallet model to avoid duplicate triggers:
      class Wallet extends Model
      {
          public static function boot()
          {
              parent::boot();
              static::observe(\Zotel\Wallet\Observers\WalletObserver::class);
          }
      }
      
  5. Migration Issues:

    • If upgrading, run php artisan wallet:migrate to handle schema changes. Always back up your database first.

Debugging Tips

  1. Enable Logging:

    • Configure config/wallet.php to log transactions:
      'log_transactions' => env('WALLET_LOG_TRANSACTIONS', true),
      
    • Check logs at storage/logs/laravel.log.
  2. Transaction Tracing:

    • Use the wallet:transactions Artisan command to inspect history:
      php artisan wallet:transactions --wallet=1 --limit=10
      
  3. Event Debugging:

    • Listen for events in Tinker to verify triggers:
      php artisan tinker
      >>> \Zotel\Wallet\Events\WalletDeposited::dispatch($wallet, 100.00, 'Test');
      

Extension Points

  1. Custom Transaction Types:

    • Extend the Transaction model to add custom fields:
      class CustomTransaction extends \Zotel\Wallet\Models\Transaction
      {
          protected $casts = [
              'metadata' => 'json',
          ];
      }
      
  2. Gateway Integration:

    • Create a custom gateway for third-party payments (e.g., PayPal, Crypto):
      namespace App\Gateways;
      
      use Zotel\Wallet\Contracts\Gateway;
      
      class PayPalGateway implements Gateway
      {
          public function processPayment($amount, $currency, $reference)
          {
              // Custom logic
          }
      }
      
  3. Webhook Handlers:

    • Register custom webhook handlers in config/wallet.php:
      'webhooks' => [
          'stripe' => \App\Handlers\StripeWebhook::class,
      ],
      
  4. Custom Commands:

    • Add CLI tools for wallet management:
      php artisan make:command WalletReport
      
      Example:
      public function handle()
      {
          $wallets = Wallet::all();
          foreach ($wallets as $wallet) {
              $this->info("Wallet {$wallet->id}: {$wallet->balance} {$wallet->currency}");
          }
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai