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

Unit Conversions Laravel Package

spatie/unit-conversions

Lightweight PHP unit conversion library by Spatie. Currently supports weight conversion from kilograms to pounds via a fluent API: Weight::fromKilograms(100)->toLbs(). Install with Composer and extend as more units are added.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:
    composer require spatie/unit-conversions
    
  2. First Use Case: Convert a weight from kilograms to pounds:
    use Spatie\UnitConversions\Weight;
    
    $weightInLbs = Weight::fromKilograms(100)->toLbs();
    // Returns: 220.4623
    

Where to Look First

  • Documentation: The README is concise but clear. Focus on the Weight class for now.
  • Source Code: Explore src/Weight.php to understand the conversion logic and available methods.

Implementation Patterns

Basic Usage

  • Chaining Methods:
    $result = Weight::fromKilograms(50)->toLbs()->toString('2 decimal places');
    // Returns: "110.23"
    
  • Precision Handling:
    $weight = Weight::fromKilograms(1.5);
    $lbs = $weight->toLbs(4); // Round to 4 decimal places
    

Integration with Laravel

  • Form Requests: Validate and convert user input in a FormRequest:

    public function rules()
    {
        return [
            'weight_kg' => 'required|numeric',
        ];
    }
    
    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            $weightLbs = Weight::fromKilograms($this->input('weight_kg'))->toLbs();
            $this->merge(['weight_lbs' => $weightLbs]);
        });
    }
    
  • Model Attributes: Store converted values as model attributes:

    class Product extends Model
    {
        protected $appends = ['weight_lbs'];
    
        public function getWeightLbsAttribute()
        {
            return Weight::fromKilograms($this->weight_kg)->toLbs();
        }
    }
    
  • API Responses: Dynamically convert units based on client preferences:

    return response()->json([
        'weight' => [
            'kg' => $product->weight_kg,
            'lbs' => Weight::fromKilograms($product->weight_kg)->toLbs(),
        ],
    ]);
    

Extending Functionality

  • Custom Unit Conversions: Create a new class (e.g., Temperature) by extending Spatie\UnitConversions\Unit:
    namespace App\UnitConversions;
    
    use Spatie\UnitConversions\Unit;
    
    class Temperature extends Unit
    {
        public static function fromCelsius(float $value): self
        {
            return new static($value);
        }
    
        public function toFahrenheit(): float
        {
            return $this->value * 9/5 + 32;
        }
    }
    

Gotchas and Tips

Pitfalls

  • Limited Scope: The package currently only supports kg to lbs conversions. Extend it for other units (e.g., temperature, length) as needed.

    • Workaround: Create custom classes (as shown above) or fork the package.
  • Precision Loss: Floating-point arithmetic can introduce rounding errors. Use round() or number_format() for consistent output:

    $weight->toLbs(2); // Ensures 2 decimal places
    
  • No Reverse Conversions: The package does not support lbs to kg conversions out of the box. Implement manually:

    Weight::fromLbs(220.4623)->toKilograms(); // Not supported; use division:
    $kg = 220.4623 / 2.204623; // ~100
    

Debugging

  • Check Input Values: Ensure input values are numeric to avoid errors:

    if (!is_numeric($input)) {
        throw new \InvalidArgumentException('Input must be numeric.');
    }
    
  • Unit Consistency: Validate units before conversion to avoid logical errors:

    if ($weight->unit !== 'kg') {
        throw new \RuntimeException('Expected kilograms, got ' . $weight->unit);
    }
    

Tips

  • Configuration: No config file is needed, but you can create a facade for cleaner usage:

    // app/Providers/AppServiceProvider.php
    public function boot()
    {
        app()->bind('weight', function () {
            return new \Spatie\UnitConversions\Weight();
        });
    }
    

    Then use:

    $weight = app('weight')->fromKilograms(100)->toLbs();
    
  • Testing: Write unit tests for conversions, especially if extending the package:

    public function testKgToLbsConversion()
    {
        $this->assertEquals(220.4623, Weight::fromKilograms(100)->toLbs());
    }
    
  • Performance: Caching converted values if the same conversions are performed repeatedly:

    $cacheKey = 'weight_' . md5($kgValue);
    $lbs = cache()->remember($cacheKey, now()->addHours(1), function () use ($kgValue) {
        return Weight::fromKilograms($kgValue)->toLbs();
    });
    
  • Documentation: Add PHPDoc blocks to custom classes for IDE autocompletion and clarity:

    /**
     * Convert Celsius to Fahrenheit.
     *
     * @return float
     */
    public function toFahrenheit(): float
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation