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

Users Profile Balance Laravel Package

baks-dev/users-profile-balance

BaksDev Profile Balance — пакет для управления балансом профилей пользователей. Установка через Composer, установка конфигурации и ресурсов командой baks:assets:install, поддержка миграций Doctrine и тестов PHPUnit. Требуется PHP 8.4+.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package

    composer require baks-dev/users-profile-balance
    

    Add auto-scripts to composer.json:

    "scripts": {
        "post-install-cmd": ["@auto-scripts"],
        "post-update-cmd": ["@auto-scripts"],
        "auto-scripts": {
            "baks:assets:install": "symfony-cmd"
        }
    }
    
  2. Run Initial Setup

    php artisan baks:assets:install
    php artisan doctrine:migrations:diff
    php artisan doctrine:migrations:migrate
    
  3. First Use Case: Create a User Balance Inject the BalanceService into a controller or command:

    use BaksDev\Balance\Services\BalanceService;
    
    public function __construct(private BalanceService $balanceService) {}
    
    public function createBalance(User $user, float $initialAmount) {
        $this->balanceService->create($user->id, $initialAmount);
    }
    
  4. Verify with Tests

    php artisan test --group=users-profile-balance
    

Implementation Patterns

Core Workflows

1. Balance CRUD Operations

Use the service layer for atomic operations:

// Create
$this->balanceService->create($userId, 100.0);

// Update (increment/decrement)
$this->balanceService->increment($userId, 50.0);
$this->balanceService->decrement($userId, 20.0);

// Retrieve
$balance = $this->balanceService->get($userId);

2. Event-Driven Extensions

Listen to balance events (if supported) to trigger side effects:

use BaksDev\Balance\Events\BalanceUpdated;

Event::listen(BalanceUpdated::class, function ($event) {
    // Send notification, log analytics, etc.
    Notification::send($event->user, new BalanceAlert($event->newBalance));
});

3. Validation and Business Logic

Override default validation rules via config (config/baks.php):

'validation' => [
    'min_balance' => 0,
    'max_balance' => 1000000,
    'allow_negative' => false,
],

4. Multi-Currency Support (If Applicable)

Extend the Balance model or service to support currency types:

$this->balanceService->create($userId, 100.0, 'points');
$this->balanceService->create($userId, 50.0, 'credits');

5. Admin Panel Integration

Use the package’s console commands for bulk operations:

# Top-up balances for all users
php artisan baks:balance:topup --user-id=1 --amount=50

# Reset balances (careful!)
php artisan baks:balance:reset --user-id=1

Integration Tips

Laravel-Specific Patterns

  1. Service Provider Binding Ensure the package’s service is bound in AppServiceProvider:

    public function register() {
        $this->app->bind(BalanceService::class, function ($app) {
            return new BalanceService(
                $app->make(BalanceRepository::class),
                $app->make(BalanceValidator::class)
            );
        });
    }
    
  2. Middleware for Balance Checks Protect routes requiring a minimum balance:

    public function handle(Request $request, Closure $next) {
        $user = $request->user();
        $balance = $this->balanceService->get($user->id);
    
        if ($balance < config('baks.min_balance')) {
            abort(403, 'Insufficient balance');
        }
    
        return $next($request);
    }
    
  3. Queue-Based Balance Updates Offload balance changes to queues for scalability:

    Queue::push(new UpdateBalanceJob($userId, -10.0));
    

    Define the job:

    class UpdateBalanceJob implements ShouldQueue {
        public function handle() {
            $this->balanceService->decrement($this->userId, $this->amount);
        }
    }
    
  4. API Resource for Balance Data Create a resource to expose balance data securely:

    public function toArray($request) {
        return [
            'amount' => $this->balanceService->get($request->user()->id),
            'currency' => 'points',
        ];
    }
    

Gotchas and Tips

Pitfalls

  1. Migration Conflicts

    • Issue: Package migrations may conflict with existing profile_balances tables.
    • Fix: Run doctrine:migrations:diff --dry-run first to preview changes. Manually resolve conflicts by:
      php artisan make:migration adjust_profile_balances_table --table=profile_balances
      
      Then merge the changes into the package’s migration.
  2. Missing Documentation

    • Issue: Lack of detailed docs means reverse-engineering is required.
    • Fix: Inspect the src/ directory for:
      • BalanceService.php (core logic).
      • BalanceRepository.php (database interactions).
      • BalanceValidator.php (rules).
    • Tip: Add PHPDoc comments to critical methods for your team.
  3. No Built-in UI

    • Issue: The package provides no frontend components.
    • Fix: Use Laravel Livewire or Inertia.js to build a balance dashboard:
      // Livewire Component
      public $balance;
      public $userId;
      
      public function mount() {
          $this->balance = $this->balanceService->get($this->userId);
      }
      
      public function topUp($amount) {
          $this->balanceService->increment($this->userId, $amount);
          $this->balance += $amount;
      }
      
  4. PHP 8.4+ Requirements

    • Issue: May break if your server uses an older PHP version.
    • Fix: Use a .php-version file or Docker to enforce PHP 8.4+:
      FROM php:8.4-fpm
      
  5. No Multi-Tenancy Support

    • Issue: Balances are user-scoped, not tenant-scoped.
    • Fix: Extend the Balance model to include a tenant_id:
      public function setTenantAttribute($value) {
          $this->attributes['tenant_id'] = $value;
      }
      

Debugging Tips

  1. Enable Debug Logging Add to config/logging.php:

    'channels' => [
        'baks' => [
            'driver' => 'single',
            'path' => storage_path('logs/baks.log'),
            'level' => 'debug',
        ],
    ],
    

    Then log balance operations:

    \Log::channel('baks')->debug('Balance updated', ['user_id' => $userId, 'new_balance' => $newBalance]);
    
  2. Database-Level Debugging Use Laravel Debugbar to inspect queries:

    if (app()->environment('local')) {
        $this->app->register(\Barryvdh\Debugbar\ServiceProvider::class);
    }
    

    Check for:

    • Long-running queries (e.g., SELECT ... FOR UPDATE locks).
    • Missing indexes on user_id or balance_type.
  3. Race Condition Handling

    • Issue: Concurrent balance updates may cause inconsistencies.
    • Fix: Use database transactions:
      DB::transaction(function () use ($userId, $amount) {
          $this->balanceService->decrement($userId, $amount);
          // Additional logic (e.g., send notification)
      });
      
  4. Testing Edge Cases Write tests for:

    • Negative balance attempts (if allow_negative = false).
    • Concurrent updates (use Laravel’s refreshModel() to simulate race conditions).
    • Expiry logic (if the package supports it):
      $this->balanceService->setExpiry($userId, now()->addDays(30));
      

Extension Points

  1. Custom Balance Types Extend the Balance model to support custom types (e.g., "loyalty_points", "premium_credits"):

    // Add to Balance model
    protected $casts = [
        'type' => 'string',
    ];
    
    // Add to migrations
    Schema::table('profile_balances', function (Blueprint $table) {
        $table->string('type')->default('points');
    });
    
  2. Webhook Triggers Dispatch events to trigger external APIs (e.g., Stripe, third-party services):

    Event::listen(BalanceUpdated::class,
    
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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony