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

Laravel Default Profile Image Laravel Package

a6digital/laravel-default-profile-image

Generate default avatar/profile images in Laravel from a user’s name (initials). Customize size, background and text colors, and optional custom font, then save via Storage or return an encoded image for immediate use.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require a6digital/laravel-default-profile-image
    

    Register the service provider in config/app.php:

    'providers' => [
        A6digital\Image\DefaultProfileImageServiceProvider::class,
    ],
    
  2. First Use Case: Generate a default avatar for a user in a controller or model:

    use DefaultProfileImage;
    
    $userName = "John Doe";
    $img = DefaultProfileImage::create($userName);
    $path = "avatars/{$userName}.png";
    Storage::put($path, $img->encode());
    

    This creates a 512x512px PNG with black background and white initials ("JD").

  3. Where to Look First:

    • README.md: For basic usage and parameter details.
    • src/DefaultProfileImage.php: Core logic for customization (e.g., size, colors, fonts).
    • tests/: Edge-case examples (e.g., Unicode names, multi-word names).

Implementation Patterns

Core Workflows

1. User Model Integration

Add a method to generate and cache avatars:

// app/Models/User.php
public function getDefaultAvatarPath()
{
    $path = "avatars/{$this->id}.png";
    if (!Storage::exists($path)) {
        $img = DefaultProfileImage::create($this->name);
        Storage::put($path, $img->encode());
    }
    return $path;
}

2. Dynamic Avatar URLs

Use Laravel’s Storage facade to generate URLs:

// In a controller or Blade template
$avatarUrl = Storage::url($user->getDefaultAvatarPath());

3. Customization via Config

Extend the package by binding a custom class in the service provider:

// app/Providers/AppServiceProvider.php
public function register()
{
    $this->app->bind('DefaultProfileImage', function ($app) {
        return new App\Services\CustomProfileImage();
    });
}

4. Bulk Generation

Use Laravel queues for async generation (e.g., during user import):

// app/Jobs/GenerateDefaultAvatars.php
public function handle()
{
    $users = User::whereNull('avatar_path')->limit(100)->get();
    foreach ($users as $user) {
        $img = DefaultProfileImage::create($user->name);
        Storage::put("avatars/{$user->id}.png", $img->encode());
        $user->update(['avatar_path' => "avatars/{$user->id}.png"]);
    }
}

Integration Tips

  • Storage Backend: Ensure your filesystems.php config points to a writable disk (e.g., local or s3).
  • Caching: Cache generated avatars in Redis or the filesystem to avoid regenerating for the same user.
  • Fallback Logic: Combine with a hasUploadedAvatar() check to prioritize user-uploaded images.
  • Testing: Mock Storage::put() in unit tests to avoid filesystem I/O:
    Storage::shouldReceive('put')->once();
    

Gotchas and Tips

Pitfalls

  1. Laravel Version Mismatch:

    • Issue: The package is unmaintained for Laravel 6+. Using it in Laravel 8+ may trigger deprecation warnings or failures.
    • Fix: Use a compatibility layer or fork the package. Example:
      // app/Providers/AppServiceProvider.php
      public function boot()
      {
          if (app()->version() >= '8.0') {
              $this->app->alias('DefaultProfileImage', App\Services\Laravel8ProfileImage::class);
          }
      }
      
  2. Unicode/Non-Latin Names:

    • Issue: Some Unicode characters (e.g., Cyrillic, CJK) may render incorrectly due to font limitations.
    • Fix: Use a Unicode-compatible font (e.g., Roboto or Noto Sans). Example:
      $img = DefaultProfileImage::create("Привет Мир", 256, '#000', '#FFF', public_path('fonts/NotoSans-Regular.ttf'));
      
  3. Font Paths:

    • Issue: Custom fonts must be accessible to the PHP process (not just the web server).
    • Fix: Use absolute paths (e.g., /var/www/fonts/) or Laravel’s storage_path():
      $fontPath = storage_path('fonts/Roboto-Regular.ttf');
      
  4. Image Size Limits:

    • Issue: Large sizes (e.g., 1024px+) may hit memory limits or fail silently.
    • Fix: Cap sizes in a wrapper class or use ini_set('memory_limit', '256M') temporarily.
  5. Storage Permissions:

    • Issue: Storage::put() may fail if the target directory lacks write permissions.
    • Fix: Ensure the storage disk is configured correctly:
      'disks' => [
          'avatars' => [
              'driver' => 'local',
              'root' => storage_path('app/avatars'),
              'permissions' => [
                  'file' => [
                      'public' => true,
                      'private' => false,
                  ],
              ],
          ],
      ],
      

Debugging

  • Blank Images: Verify the name string isn’t empty or contains only whitespace.
  • Color Issues: Ensure hex colors are valid (e.g., #FFF vs. #FFFFFF).
  • Font Loading: Check the font file exists and is readable by the PHP process:
    if (!file_exists($fontPath)) {
        throw new \RuntimeException("Font file not found at {$fontPath}");
    }
    

Extension Points

  1. Custom Initial Logic: Override how initials are extracted:

    // app/Services/CustomProfileImage.php
    public static function create($name, $size = 512, $bgColor = '#000', $textColor = '#FFF', $fontPath = null)
    {
        $initials = self::extractInitials($name); // Custom logic
        // ... rest of the method
    }
    
    protected static function extractInitials($name)
    {
        $parts = explode(' ', trim($name));
        return count($parts) > 1
            ? strtoupper(substr($parts[0], 0, 1) . substr($parts[count($parts) - 1], 0, 1))
            : strtoupper(substr($name, 0, 2));
    }
    
  2. Dynamic Colors: Use a color palette service to rotate colors per user ID:

    $palette = app(ColorPalette::class);
    $bgColor = $palette->getForUser($user->id);
    
  3. SVG Output: Extend the package to support SVG (requires custom implementation):

    // Pseudocode
    $svg = new \App\Services\SvgProfileImage($name, $size);
    Storage::put("avatars/{$user->id}.svg", $svg->render());
    

Performance Tips

  • Cache Generated Images: Store avatars in a fast disk (e.g., local with SSD) and cache URLs in Redis.
  • Batch Processing: Generate avatars in chunks during off-peak hours for large user bases.
  • Lazy Loading: Generate avatars on-demand (e.g., when a user visits their profile) rather than pre-generating for all users.

Configuration Quirks

  • Default Values: The package uses hardcoded defaults (512px, black/white). Override them globally in a wrapper:
    // app/Providers/AppServiceProvider.php
    public function boot()
    {
        DefaultProfileImage::setDefaults(256, '#212121', '#FFFFFF');
    }
    
  • Font Fallback: If a custom font fails to load, the package falls back to a default. Test this behavior with invalid paths.
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky