spatie/color
PHP library for color parsing, conversion, and comparison. Supports CSS named colors plus RGB/RGBA/ARGB, Hex, HSL/HSLA, HSB, CMYK, CIELab, and XYZ. Includes WCAG contrast ratio and Delta E distances (CIE76, CIE94, CIEDE2000).
Installation
composer require spatie/color
No configuration is needed—just require the package in your project.
Basic Usage Create a color instance from a string (hex, rgb, hsl, cmyk, or named color):
use Spatie\Color\Color;
$color = Color::fromString('#FF5733'); // Hex
$color = Color::fromString('rgb(255, 87, 51)'); // RGB
$color = Color::fromString('red'); // Named color
First Use Case Convert a hex color to RGB and check if it’s bright enough for dark mode:
$hexColor = Color::fromString('#FF5733');
$rgb = $hexColor->toRgb(); // Returns [255, 87, 51]
$isBright = $hexColor->isBright(); // true/false
Color class – Central class with static factory methods (fromString, fromRgb, etc.).isBright(), isDark(), adjustBrightness(), etc.Color Conversion Convert between formats dynamically (e.g., hex ↔ RGB ↔ HSL):
$hex = Color::fromString('rgb(255, 87, 51)')->toHex(); // '#FF5733'
$hsl = Color::fromString('#FF5733')->toHsl(); // [0, 100%, 64.51%]
Dynamic Theming Adjust brightness/contrast for UI components:
$primary = Color::fromString('#4285F4');
$darkPrimary = $primary->adjustBrightness(-20); // Darker variant
Validation & Sanitization Ensure user-uploaded colors are valid:
$inputColor = request('color');
$color = Color::fromString($inputColor) ?? abort(400, 'Invalid color');
Accessibility Checks Verify color contrast against a background:
$textColor = Color::fromString('#FFFFFF');
$bgColor = Color::fromString('#4285F4');
$contrastRatio = $textColor->contrastRatio($bgColor); // >= 4.5 for AA compliance
Laravel Views: Pass colors as objects to Blade templates for dynamic styling:
return view('dashboard', ['accentColor' => Color::fromString('#FF5733')]);
<div style="background-color: {{ $accentColor->toHex() }}">...</div>
Eloquent Models: Store colors as strings but use the package for logic:
class Product extends Model {
public function getDisplayColorAttribute() {
return Color::fromString($this->color)->adjustBrightness(10)->toHex();
}
}
API Responses: Return color objects serialized to hex/RGB for consistency:
return response()->json(['color' => Color::fromString('#FF5733')->toRgb()]);
Case Sensitivity in Hex
#FF5733 and #ff5733 are treated as identical, but invalid formats (e.g., #GHIJKL) throw exceptions. Validate input:
try {
$color = Color::fromString($userInput);
} catch (\InvalidArgumentException $e) {
// Handle invalid color
}
Named Color Limitations
Not all named colors are supported (e.g., lightblue may not work). Fall back to hex/RGB:
$color = Color::fromString('lightblue') ?? Color::fromString('#ADD8E6');
CMYK Precision CMYK conversions may introduce rounding errors. Use RGB/HSL for critical applications.
Performance
Avoid creating Color objects repeatedly in loops. Reuse instances or cache results:
$colors = collect(['#FF5733', '#33FF57'])
->map(fn ($hex) => Color::fromString($hex))
->pluck('toRgb');
Color::supportedFormats() to verify input compatibility.dd(Color::fromString('#FF5733')->toArray());
Output:
[
'hex' => '#FF5733',
'rgb' => [255, 87, 51],
'hsl' => [15, 100, 64.51],
'cmyk' => [0, 66, 80, 0],
'name' => null,
]
Custom Color Spaces
Extend the package by adding new formats (e.g., Color::fromString('hwb(0, 0%, 0%)')):
Color::addFormat('hwb', function ($value) {
// Parse HWB and return RGB array
});
Laravel Service Provider Bind the package to the container for dependency injection:
$this->app->bind(Color::class, function () {
return new Color();
});
Macros
Add reusable methods to the Color class:
Color::macro('toCssVariable', function () {
return '--color: ' . $this->toHex() . ';';
});
Usage:
echo Color::fromString('#FF5733')->toCssVariable();
// Output: --color: #FF5733;
red vs. rouge). Test edge cases.How can I help you explore Laravel packages today?