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.
composer require spatie/unit-conversions
use Spatie\UnitConversions\Weight;
$weightInLbs = Weight::fromKilograms(100)->toLbs();
// Returns: 220.4623
Weight class for now.src/Weight.php to understand the conversion logic and available methods.$result = Weight::fromKilograms(50)->toLbs()->toString('2 decimal places');
// Returns: "110.23"
$weight = Weight::fromKilograms(1.5);
$lbs = $weight->toLbs(4); // Round to 4 decimal places
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(),
],
]);
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;
}
}
Limited Scope:
The package currently only supports kg to lbs conversions. Extend it for other units (e.g., temperature, length) as needed.
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
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);
}
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
How can I help you explore Laravel packages today?