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 Money Laravel Package

elegantly/laravel-money

Laravel integration for brick/money: Eloquent casting to Brick\Money\Money, safe parsing from strings/ints/floats, and a ValidMoney validation rule with min/max bounds and nullability. Store amounts cleanly (with currency column or fixed currency).

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Strengths:

    • Precision-Centric: Aligns with financial systems requiring exact monetary calculations (e.g., invoicing, subscriptions, or payment processing) by leveraging Brick/Money, which avoids floating-point errors via integer-based storage (smallest currency unit).
    • Laravel-Native: Seamlessly integrates with Eloquent models, Form Requests, and Livewire, reducing friction for Laravel-centric teams.
    • Value-Object Paradigm: Encourages immutable Money objects, improving code clarity and reducing side-effect risks in financial operations.
    • Multi-Currency Ready: Supports dynamic or fixed currencies per model/field, enabling global scalability without architectural overhauls.
    • Validation Layer: Provides ValidMoney rule for input sanitization, critical for APIs and user-facing forms.
  • Fit Gaps:

    • Schema Dependency: Requires bigInteger + string (currency) columns for optimal precision, which may conflict with existing databases or legacy schemas.
    • Learning Curve: Developers unfamiliar with value objects or Brick/Money may need training to adopt the pattern.
    • Limited Currency Conversion: Focuses on storage/validation, not real-time conversion (would need integration with a service like ExchangeRate-API).

Integration Feasibility

  • High for Greenfield Projects: Ideal for new Laravel applications or modules where database schemas can be designed with precision in mind.
  • Moderate for Legacy Systems:
    • Database: Existing decimal/float columns would need migration to bigInteger + currency columns (backward-compatible parsing exists but sacrifices precision).
    • Codebase: Minimal changes required for new models; existing models would need incremental updates to adopt MoneyCast.
  • API/Third-Party Compatibility:
    • Input/Output: MoneyParser handles common formats (strings, ints, floats), easing integration with external systems.
    • Serialization: Money objects serialize to floats (e.g., 100.00) by default, which may require customization for APIs expecting strings (e.g., "USD 100.00").

Technical Risk

  • Low Risk for Targeted Use Cases:
    • Financial Precision: Eliminates a known pain point (floating-point errors) with a well-tested library (Brick/Money has 1.5K+ stars).
    • Validation: Reduces runtime errors from malformed monetary inputs.
  • Medium Risk for Legacy Systems:
    • Schema Migration: Converting decimal columns to bigInteger + currency requires downtime and testing.
    • Data Loss: Existing monetary values stored as floats may lose precision during migration (mitigated by rounding strategies).
  • Dependencies:
    • Brick/Money: Stable (v0.15.x) with active maintenance.
    • Laravel: Officially supports v10–12; may need minor adjustments for future versions.

Key Questions

  1. Database Schema:
    • Can existing monetary data be migrated without precision loss? If not, what rounding strategy will be used?
    • Are there constraints on adding new columns (e.g., currency) to existing tables?
  2. Currency Handling:
    • Is multi-currency support a requirement, or can currencies be fixed per model/field?
    • Are there compliance requirements (e.g., ISO 4217) for currency codes?
  3. API Contracts:
    • How should Money objects be serialized for APIs (e.g., JSON)? Will clients expect strings like "USD 100.00" or floats like 100.00?
  4. Performance:
    • Will the additional parsing/validation overhead impact high-throughput endpoints (e.g., payment processing)?
  5. Testing:
    • Are there existing tests for edge cases (e.g., negative amounts, zero-decimal currencies like JPY)?
  6. Future-Proofing:
    • Are there plans to extend this for currency conversion, exchange rates, or audit trails?

Integration Approach

Stack Fit

  • Laravel Core: Fully compatible with Eloquent, Form Requests, Livewire, and validation pipelines.
  • Database: Optimized for PostgreSQL/MySQL with bigInteger + string columns; SQLite may require adjustments for integer scaling.
  • PHP Ecosystem:
    • Dependencies: brick/money (v0.15.x), Laravel v10–12.
    • Tooling: Works with Laravel Pint, PHPStan, and CI pipelines.
  • Frontend: Validation rules (ValidMoney) integrate with Livewire, Inertia.js, or vanilla Laravel forms.

Migration Path

  1. Assessment Phase:
    • Audit existing monetary fields (identify decimal/float columns, precision requirements).
    • Define scope (e.g., start with invoices/subscriptions, then expand to orders).
  2. Schema Migration:
    • New Projects: Design tables with bigInteger (amount) + string (currency) from day one.
    • Legacy Projects:
      • Add new columns (amount_in_cents, currency) to tables.
      • Use a data migration to populate amount_in_cents from existing values (with rounding).
      • Deprecate old columns incrementally.
    • Example migration:
      Schema::table('orders', function (Blueprint $table) {
          $table->bigInteger('amount_in_cents')->nullable()->after('amount');
          $table->string('currency', 3)->nullable()->after('amount_in_cents');
      });
      
  3. Model Integration:
    • Update models to use MoneyCast:
      protected $casts = [
          'amount' => MoneyCast::of('currency'), // Dynamic currency
          // OR
          'price' => MoneyCast::of('USD'),       // Fixed currency
      ];
      
    • For legacy data, implement a fallback parser (e.g., MoneyParser::parse($model->amount * 100, $model->currency)).
  4. Validation Layer:
    • Replace custom validation logic with ValidMoney:
      'price' => ['required', new ValidMoney(min: 0, max: 10000)],
      
  5. API/Serialization:
    • Customize Money serialization if needed (e.g., override toJson() or use accessors).
    • Example accessor:
      public function getAmountStringAttribute(): string
      {
          return $this->amount->getAmount()->toString() . ' ' . $this->currency;
      }
      
  6. Testing:
    • Add tests for:
      • Precision (e.g., 0.01 USD vs. 0.02 USD calculations).
      • Edge cases (negative amounts, null values, invalid currencies).
      • Serialization/deserialization round-trips.

Compatibility

  • Laravel Versions: Officially supports v10–12; may work with v9 with minor adjustments.
  • PHP Versions: Requires PHP 8.1+ (due to Brick/Money dependencies).
  • Database: Tested on PostgreSQL/MySQL; SQLite may need integer scaling tweaks.
  • Third-Party Libraries:
    • Payment Gateways: Most (Stripe, PayPal) expect amounts in cents, aligning with this package’s design.
    • Reporting Tools: May require custom formatting for Money objects in exports.

Sequencing

  1. Phase 1: Core Models (2–4 weeks):
    • Migrate critical financial models (e.g., Invoice, Subscription, Order).
    • Implement MoneyCast and validation.
  2. Phase 2: APIs/Forms (1–2 weeks):
    • Update API responses and form validation to use ValidMoney.
    • Customize serialization if needed.
  3. Phase 3: Legacy Data (1–2 weeks):
    • Backfill amount_in_cents for existing records.
    • Deprecate old columns.
  4. Phase 4: Edge Cases (1 week):
    • Handle multi-currency scenarios, negative amounts, and audit logging.
    • Add monitoring for precision issues.

Operational Impact

Maintenance

  • Pros:
    • Reduced Bugs: Eliminates floating-point errors in monetary calculations.
    • Consistent Validation: Centralized ValidMoney rule reduces duplicate validation logic.
    • Future Extensibility: Easy to add features like currency conversion or audit trails.
  • Cons:
    • Schema Changes: Future database migrations may require coordination with other teams.
    • Dependency Updates: Must monitor Brick/Money and Laravel for breaking changes (e.g., v2.0.0’s namespace shift).

Support

  • Developer Onboarding:
    • Training Needed: Developers must understand value objects and Brick/Money’s API (e.g., Money::add(), Money::getAmount()).
    • Documentation: Package includes README, but internal docs may be needed for custom use cases (e.g., serialization).
  • Common Issues:
    • Precision Loss: Legacy data
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky