- How do I install brick/math in a Laravel 10+ project?
- Run `composer require brick/math` in your project root. The package requires PHP 8.2+ and works seamlessly with Laravel 10+. No additional Laravel-specific setup is needed beyond Composer installation.
- Will brick/math replace PHP’s native float/int types in Laravel models?
- No, it’s designed to complement them. Use `BigDecimal` or `BigInteger` for precision-critical fields (e.g., monetary values) while keeping native types for non-critical calculations. Wrap them in DTOs or accessors for consistency.
- Does brick/math work with Laravel’s validation rules?
- Yes. Create custom validators (e.g., `BigDecimalRule`) to enforce precision constraints. For example, validate a `price` field by converting it to `BigDecimal::of((string) $value)` and catching `MathException` for invalid inputs.
- What’s the performance impact if GMP/BCMath isn’t available in production?
- The library falls back to pure-PHP calculations, which are slower but still correct. Benchmark your use case—financial apps may tolerate the overhead, while high-frequency systems should ensure GMP/BCMath is enabled.
- How do I handle rounding errors when converting floats to BigDecimal?
- Use `BigDecimal::fromFloatExact()` for strict conversion (throws on lossy operations) or `fromFloatShortest()` for approximate rounding. Avoid `BigDecimal::of((string) $float)` as it may silently truncate precision.
- Can brick/math be used with Laravel’s Money package (moneyphp/money)?
- Yes, but avoid mixing them directly. Use `BigDecimal` for internal calculations and convert to `Money` for API responses or storage. Example: `Money::USD($bigDecimal->toString())`.
- What’s the best way to migrate from float/int to brick/math in Laravel?
- Start with a single service class (e.g., `app/Services/ArbitraryMath.php`) to isolate high-risk calculations. Gradually replace legacy logic, validating results against old outputs. Use middleware to sanitize incoming data into `BigDecimal` early.
- How should I serialize BigDecimal/BigInteger for APIs or databases?
- Store as strings (e.g., `toString()`) in databases or JSON APIs. Avoid serializing objects directly, as PHP’s `serialize()` may lose precision. For databases, use `TEXT` or `DECIMAL` columns with sufficient scale.
- Are there breaking changes between 0.x.y versions of brick/math?
- Yes. Each `0.x.0` release may introduce breaking changes (e.g., `BigInteger::mod()` semantics). Lock to a patch version (e.g., `^0.17`) in `composer.json` to avoid surprises. Check the [release history](https://github.com/brick/math/releases) before upgrading.
- What alternatives exist for arbitrary-precision math in Laravel?
- For PHP 8.2+, `brick/math` is the most modern and Laravel-friendly option. Older alternatives include `php-gmp` (lower-level) or `bcmath` (built-in but less flexible). For JavaScript interop, consider `bignumber.js` on the frontend.