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 Steps

  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 facade alias.)

  2. First Usage: Generate a base64-encoded avatar from a name in a Blade view:

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

    (Outputs a circular image with initials "JD" on a random background.)

  3. Key Files:

    • config/laravolt/avatar.php (published via php artisan vendor:publish)
    • app/Avatar.php (facade for fluent method chaining).

First Use Case: User Profile Avatars

Scenario: Display consistent avatars for users in a dashboard. Implementation:

// In a User model or controller:
$avatarUrl = Avatar::create($user->name)
    ->setDimension(80)
    ->setShape('square')
    ->toBase64();

// In Blade:
<img src="{{ $avatarUrl }}" class="user-avatar" />

Why?

  • Avoids external dependencies (e.g., Gravatar).
  • Customizable via config/themes.
  • Lightweight (no API calls).

Implementation Patterns

Core Workflows

1. Dynamic Avatar Generation

Pattern: Chain methods for runtime customization.

// Dynamic sizing based on context
$avatar = Avatar::create($user->name)
    ->setDimension($user->isPremium() ? 120 : 80)
    ->setTheme($user->preferredTheme ?? 'colorful')
    ->toBase64();

Use Case: Adapt avatars to UI themes or user preferences.

2. Gravatar Fallback

Pattern: Hybrid approach for existing Gravatar users.

$email = $user->email;
$avatar = Avatar::create($email)
    ->toGravatar(['d' => Avatar::create($user->name)->toBase64()]); // Fallback to custom avatar

Use Case: Migrate users from Gravatar to self-hosted avatars gradually.

3. SVG for Scalability

Pattern: Use SVG for resolution-independent avatars.

// In Blade:
<div class="avatar-container">
    {!! Avatar::create($user->name)
        ->setResponsive()
        ->setFontFamily('Roboto')
        ->toSvg() !!}
</div>

CSS:

.avatar-container svg {
    width: 100%;
    height: auto;
}

Use Case: Retina displays or responsive designs.

4. Caching Strategies

Pattern: Cache generated avatars to reduce load.

// Cache for 1 hour
$cachedAvatar = Cache::remember("avatar_{$user->id}", now()->addHour(), function() use ($user) {
    return Avatar::create($user->name)->toBase64();
});

Use Case: High-traffic applications (e.g., social networks).


Integration Tips

Laravel Ecosystem

  • Eloquent Models: Add an accessor to User model:

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

    Usage: <img src="{{ $user->avatar }}" />.

  • API Responses: Return avatars in JSON:

    return response()->json([
        'user' => $user,
        'avatar' => Avatar::create($user->name)->toBase64(),
    ]);
    

Non-Laravel PHP

require 'vendor/autoload.php';
$avatar = new \Laravolt\Avatar\Avatar(['driver' => 'gd']);
echo $avatar->create('Jane Doe')->toSvg();

Theming Systems

  • Dynamic Themes: Override themes in runtime:
    Avatar::create($user->name)
        ->setTheme([
            'backgrounds' => [$user->favoriteColor],
            'foregrounds' => ['#000000'],
        ])
        ->toBase64();
    

Storage Integration

  • Filesystem Storage: Save avatars to disk:
    $path = Avatar::create($user->name)
        ->save(storage_path("app/avatars/{$user->id}.png"));
    

Gotchas and Tips

Pitfalls

  1. Font Handling:

    • Issue: Non-ASCII characters (e.g., José) may render incorrectly.
    • Fix: Set 'ascii' => true in config or use fonts supporting Unicode (e.g., Noto Sans).
  2. Image Driver Conflicts:

    • Issue: Imagick may not be available on shared hosting.
    • Fix: Force gd driver in config:
      'driver' => 'gd',
      
  3. SVG Caching:

    • Issue: SVG avatars may not cache effectively due to dynamic content.
    • Fix: Use Cache::put() with a unique key (e.g., hashed name + config).
  4. Gravatar Hashing:

    • Issue: Gravatar URLs break if email changes.
    • Fix: Cache Gravatar URLs separately from custom avatars.
  5. Performance:

    • Issue: Generating avatars on-the-fly can slow down views.
    • Fix: Pre-generate avatars during user creation or use a queue job.

Debugging Tips

  1. Inspect Generated Images:

    $image = Avatar::create('Test')->getImageObject();
    $image->save(storage_path('debug-avatar.png')); // Save for inspection
    
  2. Check Config Overrides:

    • Runtime overrides (e.g., setTheme()) take precedence over config.
    • Verify with:
      Avatar::create('Test')->getAttribute('theme');
      
  3. Font Paths:

    • Ensure font paths in config/laravolt/avatar.php are absolute and accessible by the web server.
  4. Gravatar Parameters:

    • Validate Gravatar parameters against official docs.
    • Example debug:
      echo Avatar::create('test@example.com')->toGravatar();
      

Extension Points

  1. Custom Generators:

    • Extend \Laravolt\Avatar\Generator\DefaultGenerator to create unique styles (e.g., pixel art).
    • Register in config:
      'generator' => App\Generators\PixelAvatar::class,
      
  2. Theme Extensions:

    • Add themes to config/laravolt/avatar.php:
      'themes' => [
          'monochrome' => [
              'backgrounds' => ['#000000'],
              'foregrounds' => ['#FFFFFF'],
          ],
      ],
      
  3. Intervention Image Hooks:

    • Modify the Intervention image object before rendering:
      $image = Avatar::create('Test')->getImageObject();
      $image->filters()->sepia(); // Apply filters
      $image->toBase64();
      
  4. Event Listeners:

    • Trigger events for avatar generation (e.g., log usage):
      Avatar::creating(function ($name) {
          Log::debug("Generating avatar for: $name");
      });
      
    • Note: Requires extending the package or using Laravel events.
  5. Caching Layer:

    • Implement a custom cache driver for avatars:
      Avatar::create('Test')->setCacheDriver('redis')->toBase64();
      
    • Note: Requires patching the package or using middleware.

Pro Tips

  1. Consistent Hashing:

    • Use a deterministic hash of the name/email for caching:
      $cacheKey = md5($user->name . $user->email);
      
  2. Dark Mode Support:

    • Add a dark theme:
      'themes' => [
          'dark' => [
              'backgrounds' => ['#1a1a1a'],
              'foregrounds' => ['#ffffff'],
          ],
      ],
      
    • Toggle via JS:
      document.body.classList.toggle('dark-mode');
      Avatar.create('User').setTheme('dark').toBase64();
      
  3. Accessibility:

    • Add ARIA labels and fallbacks:
      <img
          src="{{ Avatar::create($user->name)->toBase64() }}"
          alt="{{ $user->name }} avatar"
          loading="lazy"
          width="80"
          height="80"
      />
      
  4. Batch Generation:

    • Pre-generate avatars for all users via Artisan command:
      use Laravolt\
      
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.
codraw/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony