Weave 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

Randomcolor Laravel Package

mistic100/randomcolor

Generate attractive random colors in PHP (port of David Merfield’s randomColor). Create single or multiple colors with options for hue, luminosity, alpha, and output formats like hex, rgb(a), hsl(a), or hsv(a). Supports custom PRNG.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:
    composer require mistic100/randomcolor
    
  2. First Usage:
    use Colors\RandomColor;
    
    // Generate a single hex color
    $color = RandomColor::one();
    echo $color; // e.g., "#e74c3c"
    
  3. Basic Configuration:
    // Generate a light blue color in RGB format
    $color = RandomColor::one([
        'luminosity' => 'light',
        'hue' => 'blue',
        'format' => 'rgbCss'
    ]);
    echo $color; // e.g., "rgb(135, 206, 235)"
    

Where to Look First

First Use Case

Dynamic Chart Colors in Laravel:

// In a controller or service
$chartColors = RandomColor::many(5, [
    'hue' => ['blue', 'green', 'purple'],
    'luminosity' => 'light',
    'format' => 'hex'
]);

// Pass to Blade view
return view('dashboard', ['colors' => $chartColors]);
<!-- In Blade template -->
@foreach ($colors as $color)
    <div style="background-color: {{ $color }}; width: 50px; height: 50px;"></div>
@endforeach

Implementation Patterns

Usage Patterns

  1. Single Color Generation:

    // Hex format (default)
    $hexColor = RandomColor::one();
    
    // RGB format for CSS
    $rgbColor = RandomColor::one(['format' => 'rgbCss']);
    
    // HSL format for design tools
    $hslColor = RandomColor::one(['format' => 'hsl']);
    
  2. Color Palettes:

    // Generate 10 green shades
    $palette = RandomColor::many(10, [
        'hue' => 'green',
        'format' => 'hex'
    ]);
    
    // Generate colors from multiple hues
    $mixedPalette = RandomColor::many(8, [
        'hue' => ['red', 'blue', 'yellow'],
        'luminosity' => 'random'
    ]);
    
  3. Accessibility-Focused Colors:

    // High-contrast colors for dark mode
    $darkColors = RandomColor::many(3, [
        'luminosity' => 'dark',
        'format' => 'hex',
        'hue' => 'random'
    ]);
    
    // Ensure sufficient contrast (pair with a validation library)
    
  4. Transparent Colors:

    // RGBA for overlays
    $rgbaColor = RandomColor::one([
        'format' => 'rgbaCss',
        'alpha' => 0.5 // 50% transparency
    ]);
    
    // Hex with alpha
    $hexaColor = RandomColor::one([
        'format' => 'hexa',
        'alpha' => 0.7
    ]);
    

Workflows

  1. Laravel Service Integration:

    // app/Services/ColorService.php
    class ColorService {
        public function generatePalette(int $count, array $options = []): array {
            return RandomColor::many($count, $options);
        }
    
        public function generateSingle(array $options = []): string {
            return RandomColor::one($options);
        }
    }
    

    Register in AppServiceProvider:

    public function register() {
        $this->app->singleton(ColorService::class, function ($app) {
            return new ColorService();
        });
    }
    
  2. Blade Directives:

    // app/Providers/BladeServiceProvider.php
    Blade::directive('color', function ($expression) {
        return "<?php echo \\Colors\\RandomColor::one({$expression}); ?>";
    });
    

    Usage in Blade:

    <div style="background-color: @color(['hue' => 'blue'])"></div>
    
  3. Eloquent Model Accessors:

    // app/Models/User.php
    public function getColorAttribute() {
        return RandomColor::one([
            'hue' => $this->preferred_color ?? 'random',
            'format' => 'hex'
        ]);
    }
    

    Usage:

    $user->color; // e.g., "#3498db"
    
  4. API Responses:

    // In a controller
    return response()->json([
        'data' => [
            'color' => RandomColor::one(['format' => 'hex']),
            'rgba' => RandomColor::one(['format' => 'rgbaCss'])
        ]
    ]);
    

Integration Tips

  1. Consistent Formatting:

    • Standardize on one format (e.g., hex) for API responses to avoid client-side parsing.
    • Use format option to match frontend requirements (e.g., rgbCss for Tailwind).
  2. Caching:

    // Cache colors for 1 hour to reduce generation overhead
    $colors = Cache::remember("color_palette_{$userId}", now()->addHours(1), function () use ($userId) {
        return RandomColor::many(5, [
            'hue' => 'blue',
            'format' => 'hex'
        ]);
    });
    
  3. Seeded Randomness:

    // For reproducible colors (e.g., testing)
    $color = RandomColor::one([
        'prng' => function() {
            return 42; // Fixed seed
        },
        'format' => 'hex'
    ]);
    
  4. Validation:

    • Pair with a library like spatie/color to validate generated colors for accessibility (e.g., WCAG contrast ratios).
  5. Frontend Sync:

    • Pass colors to JavaScript via Blade data attributes:
      <div data-color="{{ json_encode(RandomColor::one(['format' => 'rgbaCss'])) }}"></div>
      
    • Or via API responses for SPAs.

Gotchas and Tips

Pitfalls

  1. PHP Version Warnings:

    • Issue: PHP 8+ may trigger warnings for implicit type conversions.
    • Fix: Update to the latest version (1.0.6+ fixes these issues).
  2. Alpha Channel Quirks:

    • Issue: Alpha values are ignored in non-alpha formats (e.g., hex).
    • Fix: Always specify format when using alpha (e.g., rgbaCss or hexa).
  3. Hue Array Behavior:

    • Issue: If hue is an array, one hue is selected randomly. Empty array = random hue.
    • Fix: Explicitly pass hues if deterministic selection is needed.
  4. Luminosity "Random":

    • Issue: luminosity: 'random' may produce unexpected results (e.g., very dark colors).
    • Fix: Use luminosity: 'light' or luminosity: 'bright' for predictable outputs.
  5. Color Repetition:

    • Issue: RandomColor::many() may generate duplicates, especially with limited hues.
    • Fix: Use a larger hue array or add a deduplication step:
      $uniqueColors = array_unique(RandomColor::many(10, ['hue' => 'blue']));
      

Debugging

  1. Unexpected Colors:

    • Debug: Check the prng option or ensure no custom logic is overriding defaults.
    • Tool: Use the demo to test options interactively.
  2. Format Mismatches:

    • Debug: Verify the format option matches frontend expectations (e.g., rgbCss vs. rgb).
    • Fix: Use var_dump() to inspect the output format:
      var_dump(RandomColor::one(['format' => 'rgbCss'])); // string(12) "rgb(123,45,67)"
      
  3. Performance Issues:

    • Debug: Profile with microtime() if generating colors in loops:
      $start = microtime(true);
      $colors = RandomColor::many(1000);
      echo microtime(true) - $start; // Should be < 0.1s
      
    • Fix: Cache results or batch generation.

Config Quirks

  1. Default Values:
    • Hue: Defaults to random (0–360).
    • Luminosity: Defaults to random (0–
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.
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator