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

Placeholder Image Laravel Package

reddatas/placeholder-image

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require reddatas/placeholder-image
    

    The package auto-registers via Laravel’s service provider discovery.

  2. First Use Case: Generate a placeholder image for missing avatars or product thumbnails by visiting:

    /placeholder/200/200/User%20Name/eeeeee/333333
    

    (URL-encoded text: User NameUser%20Name)

  3. Where to Look First:

    • Route: Check routes/web.php for the auto-registered route (placeholder/{width}/{height?}/{text?}/{bgColor?}/{textColor?}).
    • Configuration: No config file exists; defaults are hardcoded (e.g., fallback colors, text formatting).
    • Source: Review vendor/reddatas/placeholder-image/src/ for core logic (e.g., PlaceholderImageService.php).

Implementation Patterns

Usage Patterns

  1. Dynamic Placeholders in Views:

    // Blade template for user avatars
    <img src="{{ route('placeholder', [
        'width' => 100,
        'height' => 100,
        'text' => auth()->user()->name ?? 'Guest',
        'bgColor' => 'f0f0f0',
        'textColor' => '333'
    ]) }}" alt="Avatar">
    
    • Pro Tip: Cache the generated URLs (e.g., Str::of($user->name)->slug('-')) to avoid regenerating for the same user.
  2. API Responses: Return placeholder URLs in JSON:

    return response()->json([
        'image_url' => route('placeholder', [
            'width'  => 800,
            'height' => 600,
            'text'   => 'Product Image',
        ]),
    ]);
    
  3. Fallback for Missing Images:

    // In a controller or service
    public function getImageUrl($entity, $defaultText = 'No Image') {
        return route('placeholder', [
            'width'  => 300,
            'height' => 300,
            'text'   => $entity->name ?? $defaultText,
        ]);
    }
    

Workflows

  • Image Optimization: Combine with Laravel’s Image facade to resize placeholders before serving:

    use Intervention\Image\Facades\Image;
    
    $img = Image::make(public_path('placeholder.png'));
    $img->resize(400, 400)->save();
    

    (Note: This requires manual handling since the package generates images on-the-fly via HTTP.)

  • Localization: Override text defaults in a middleware:

    public function handle($request, Closure $next) {
        if ($request->routeIs('placeholder') && $request->text === null) {
            $request->merge(['text' => __('messages.placeholder_text')]);
        }
        return $next($request);
    }
    

Integration Tips

  • Caching: Use Laravel’s cache to store generated images (e.g., Cache::remember()) to reduce server load for repeated requests.

    $cacheKey = "placeholder_{$width}_{$height}_{$text}";
    return Cache::remember($cacheKey, now()->addHours(1), function() use ($width, $height, $text) {
        return route('placeholder', compact('width', 'height', 'text'));
    });
    
  • Testing: Mock the route in PHPUnit:

    $response = $this->get('/placeholder/100/100/Test');
    $response->assertStatus(200);
    $response->assertHeader('Content-Type', 'image/png');
    

Gotchas and Tips

Pitfalls

  1. URL Encoding:

    • Issue: Spaces or special characters in text (e.g., Hello World) break the URL unless encoded.
    • Fix: Always URL-encode dynamic text:
      $text = urlencode('Hello World');
      route('placeholder', ['text' => $text]);
      
    • Alternative: Use Str::of($text)->replace(' ', '-') for slug-like placeholders.
  2. Color Format:

    • Issue: Colors must be 3 or 6-digit hex (e.g., 333 or 333333). Shorthand like #abc or RGB values (rgb(0,0,0)) are unsupported.
    • Fix: Validate inputs:
      $bgColor = preg_match('/^#[0-9a-f]{3,6}$|^[0-9a-f]{3,6}$/i', $bgColor)
          ? $bgColor
          : 'cccccc'; // Default fallback
      
  3. No Height Provided:

    • Behavior: Defaults to a square image (width === height).
    • Gotcha: Unexpected aspect ratios if height is omitted. Always specify height for non-square images.
  4. Performance:

    • Issue: Generating images on every request can be slow for high-traffic routes.
    • Mitigation:
      • Cache responses aggressively (e.g., Cache::forever() for static placeholders).
      • Use a CDN to offload image generation.
  5. No Configuration:

    • Limitation: Hardcoded defaults (e.g., font, padding) cannot be changed without modifying the package source.
    • Workaround: Extend the service class or fork the package.

Debugging

  • Check Headers: Inspect the Content-Type header in the response. If it’s not image/png, the image generation failed.
    curl -I http://your-app.test/placeholder/100/100
    
  • Log Errors: Wrap the route call in a try-catch to log failures:
    try {
        $image = file_get_contents(route('placeholder', [...]));
    } catch (\Exception $e) {
        Log::error("Placeholder generation failed: " . $e->getMessage());
    }
    

Extension Points

  1. Custom Fonts: Override the PlaceholderImageService to load a custom font:

    // In a service provider
    $this->app->bind('Reddatas\PlaceholderImage\PlaceholderImageService', function () {
        $service = new \Reddatas\PlaceholderImage\PlaceholderImageService();
        $service->setFont(public_path('fonts/custom.ttf'));
        return $service;
    });
    
  2. Add Parameters: Extend the route to support additional options (e.g., borderColor):

    // In a custom service
    public function generate($width, $height, $text, $bgColor, $textColor, $borderColor = null) {
        // Implement border logic
    }
    

    Update the route in routes/web.php:

    Route::get('/placeholder/{width}/{height?}/{text?}/{bgColor?}/{textColor?}/{borderColor?}', [PlaceholderController::class, 'show']);
    
  3. Output Formats: Modify the service to support JPEG/WebP:

    // In PlaceholderImageService.php
    public function getImage($width, $height, $format = 'png') {
        switch ($format) {
            case 'jpg':
                return $this->generateJpeg($width, $height);
            case 'webp':
                return $this->generateWebP($width, $height);
            default:
                return $this->generatePng($width, $height);
        }
    }
    

    Update the route to accept a format parameter.

Config Quirks

  • No Config File: All settings (e.g., default colors, font) are in PlaceholderImageService.php. To change them:

    1. Publish the package (if supported; check config/ after installation).
    2. Fork the package and override the service class.
    3. Use environment variables to pass values (e.g., config('placeholder.default_bg')).
  • Default Values: Hardcoded defaults:

    // In PlaceholderImageService.php
    private $defaultBgColor = 'cccccc';
    private $defaultTextColor = '333333';
    private $defaultText = 'Placeholder';
    

    Override them by extending the class or using dependency injection.

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.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php