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

Avatar Laravel Package

laravolt/avatar

Generate unique placeholder avatars from names or emails using initials, with customizable colors/fonts/sizes. Works in Laravel/Lumen or any PHP app. Output as base64 data URI, save PNG/JPG files, or fall back to Gravatar for email-based avatars.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laravolt/avatar
    

    (Laravel 5.5+ auto-discovers the package; for older versions, register Laravolt\Avatar\ServiceProvider in config/app.php and add the Avatar facade.)

  2. First Use Case: Generate an avatar from a name in a Blade view:

    <img src="{{ Avatar::create('John Doe')->toBase64() }}" alt="Avatar" />
    

    (Outputs a data-URI with a circular avatar showing "JD" in a colored background.)

  3. Key Files:

    • config/laravolt/avatar.php (published via php artisan vendor:publish --provider="Laravolt\Avatar\ServiceProvider").
    • README.md for quick reference.

Implementation Patterns

Core Workflows

  1. Dynamic Avatar Generation:

    // In a controller or service
    $avatarUrl = Avatar::create($user->name)
        ->setDimension(80, 80)
        ->setTheme('grayscale-light')
        ->toBase64();
    

    (Chain methods for reusable configurations.)

  2. Gravatar Fallback:

    $gravatarUrl = Avatar::create($user->email)->toGravatar(['d' => 'retro']);
    

    (Useful for hybrid systems where Gravatar exists but initials are a fallback.)

  3. SVG for Scalability:

    <div class="avatar-container">
      {!! Avatar::create('Jane Smith')->setResponsive()->toSvg() !!}
    </div>
    

    (SVG avatars scale without pixelation; use setResponsive() for fluid layouts.)

  4. Themed Avatars:

    Avatar::create('Team Lead')
        ->setTheme(['colorful', 'grayscale-dark'])
        ->toBase64();
    

    (Randomly picks from themes for visual variety.)


Integration Tips

  1. Caching: Use Laravel’s cache for performance:

    $cacheKey = 'avatar_' . md5($user->name);
    $avatar = Cache::remember($cacheKey, now()->addHours(1), function() use ($user) {
        return Avatar::create($user->name)->toBase64();
    });
    
  2. User Model Accessor: Add to User.php:

    public function getAvatarAttribute()
    {
        return Avatar::create($this->name)->toBase64();
    }
    

    (Access via $user->avatar in Blade.)

  3. Storage Integration: Save avatars to disk for reuse:

    $path = storage_path('app/avatars/' . $user->id . '.png');
    Avatar::create($user->name)->save($path);
    

    (Use getImageObject() for advanced Intervention Image manipulations.)

  4. Non-ASCII Handling: Enable ASCII conversion in config/laravolt/avatar.php:

    'ascii' => true,
    

    (Ensures compatibility with names like "José" or "Naïve".)


Gotchas and Tips

Pitfalls

  1. Font Dependencies:

    • Issue: Non-ASCII characters may render incorrectly if fonts lack support.
    • Fix: Use ascii: true in config or ensure fonts (e.g., OpenSans-Bold.ttf) cover target characters.
    • Debug: Test with Avatar::create('José')->toSvg() and inspect the SVG output.
  2. Image Driver Conflicts:

    • Issue: gd vs. imagick may fail silently if PHP lacks extensions.
    • Fix: Verify extension_loaded('gd') or extension_loaded('imagick') in config/laravolt/avatar.php.
    • Fallback: Set 'driver' => 'gd' in config if Imagick is unavailable.
  3. SVG Styling:

    • Issue: Custom fonts in SVG may not load if paths are incorrect.
    • Fix: Use absolute paths (e.g., public_path('fonts/OpenSans-Bold.ttf')) or Google Fonts:
      <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@700&display=swap" rel="stylesheet">
      
      Then set setFontFamily('Open Sans').
  4. Gravatar Hashing:

    • Issue: Gravatar URLs may break if email formats change (e.g., user@example.com vs. user@sub.example.com).
    • Fix: Normalize emails before hashing:
      $email = strtolower(trim($user->email));
      
  5. Caching Quirks:

    • Issue: Cached avatars may not update if the cache key depends on mutable data (e.g., $user->name).
    • Fix: Use immutable identifiers like $user->id or hash the name:
      $cacheKey = 'avatar_' . md5($user->name . '_' . $user->updated_at);
      

Debugging Tips

  1. Inspect SVG Output:

    $svg = Avatar::create('Test User')->toSvg();
    file_put_contents('debug.svg', $svg);
    

    (Open debug.svg to verify font/color rendering.)

  2. Log Configuration:

    \Log::info('Avatar Config:', config('laravolt.avatar'));
    

    (Ensures your config is loaded correctly.)

  3. Intervention Image Debugging:

    $image = Avatar::create('Debug')->getImageObject();
    $image->save(storage_path('debug.png')); // Save for inspection
    

Extension Points

  1. Custom Generators: Extend \Laravolt\Avatar\Generator\DefaultGenerator to create unique styles (e.g., pixel art, monogram layouts).

  2. Dynamic Themes: Add themes to config/laravolt/avatar.php:

    'themes' => [
        'monochrome' => [
            'backgrounds' => ['#000000'],
            'foregrounds' => ['#FFFFFF'],
            'shape' => 'square',
        ],
    ];
    
  3. Storage Adapters: Wrap save() in a custom class to support S3, database storage, etc.:

    class AvatarStorage {
        public static function saveToS3($name, $content) {
            // Implement S3 logic
        }
    }
    
  4. Blade Directives: Create a Blade directive for concise usage:

    Blade::directive('avatar', function ($expression) {
        return "<?php echo Avatar::create({$expression})->toBase64(); ?>";
    });
    

    (Usage: @avatar($user->name) in Blade.)


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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai