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 Avatar Laravel Package

vigstudio/laravel-avatar

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require vigstudio/laravel-avatar
    

    Publish the config (if needed):

    php artisan vendor:publish --tag=avatar-config
    
  2. Basic Usage: Generate an avatar from a string (e.g., name or email):

    use Vigstudio\Avatar\Facades\Avatar;
    
    $avatarUrl = Avatar::create('John Doe')->toUrl();
    // Output: Gravatar-style URL (e.g., "https://www.gravatar.com/avatar/...")
    
  3. First Use Case: Display a user’s avatar in a Blade template:

    <img src="{{ Avatar::create(auth()->user()->name)->toUrl() }}" alt="Avatar">
    

Key Configurations

Check config/avatar.php for:

  • Default avatar service (Gravatar, local storage, or custom).
  • Fallback options (e.g., initials, emoji, or placeholder images).
  • Custom domains or paths for local storage.

Implementation Patterns

Common Workflows

  1. Dynamic Avatar Generation: Use middleware or a trait to attach avatars to user models:

    // In User model
    public function avatarUrl()
    {
        return Avatar::create($this->name)->toUrl();
    }
    
  2. Local Storage Integration: Cache avatars locally for performance:

    $avatar = Avatar::create('Jane Doe')
        ->setService('local')
        ->setPath(storage_path('app/avatars'))
        ->save();
    
  3. Fallback Logic: Chain fallback methods for robustness:

    $avatar = Avatar::create('A')
        ->fallback('initials')
        ->fallback('emoji')
        ->toUrl();
    
  4. Blade Directives: Create a custom Blade directive for reuse:

    // In AppServiceProvider
    Blade::directive('avatar', function ($expression) {
        return "<?php echo \\Vigstudio\\Avatar\\Facades\\Avatar::create({$expression})->toUrl(); ?>";
    });
    

    Usage:

    <img src="{{ avatar($user->name) }}">
    

Integration Tips

  • API Responses: Attach avatar URLs to JSON responses:

    return User::find(1)->append('avatar_url');
    

    (Requires adding avatar_url to $appends in the User model.)

  • Caching: Cache avatar URLs in Redis or the app cache to avoid regenerating:

    $cacheKey = "avatar:{$user->email}";
    $avatarUrl = Cache::remember($cacheKey, now()->addHours(1), function () use ($user) {
        return Avatar::create($user->email)->toUrl();
    });
    
  • Testing: Mock the Avatar facade in tests:

    $this->mock(\Vigstudio\Avatar\Facades\Avatar::class, function ($mock) {
        $mock->shouldReceive('create')->andReturnSelf();
        $mock->shouldReceive('toUrl')->andReturn('mock-avatar.jpg');
    });
    

Gotchas and Tips

Pitfalls

  1. Gravatar Dependencies:

    • If using Gravatar, ensure the hash method works correctly (e.g., md5(strtolower(trim($email)))).
    • Gravatar may block requests if the domain isn’t whitelisted (check Gravatar’s API docs).
  2. Local Storage Permissions:

    • Ensure the storage/app/avatars directory is writable:
      chmod -R 755 storage/app/avatars
      
    • Clear cached configs after changing paths:
      php artisan config:clear
      
  3. Caching Issues:

    • Local avatars won’t update until the cache is cleared or the file is manually deleted.
    • Use unique filenames (e.g., include a hash of the input) to avoid conflicts:
      $filename = md5($user->email).'.png';
      
  4. Fallback Overrides:

    • Custom fallbacks (e.g., initials) may conflict with existing methods. Check the source for available options.

Debugging

  • Log Avatar URLs: Temporarily log URLs to debug issues:

    \Log::debug('Avatar URL', ['url' => Avatar::create('Test')->toUrl()]);
    
  • Validate Inputs: Sanitize inputs to avoid edge cases (e.g., empty strings, special characters):

    $name = trim($user->name ?? '');
    if (empty($name)) {
        $name = 'Anonymous';
    }
    

Extension Points

  1. Custom Services: Extend the package by adding a new service provider:

    // config/avatar.php
    'services' => [
        'custom' => \App\Services\CustomAvatarService::class,
    ],
    

    Implement the Vigstudio\Avatar\Contracts\AvatarService interface.

  2. Avatar Customization: Override the default avatar generator (e.g., for monogram avatars):

    Avatar::create('John Doe')
        ->setService('local')
        ->setGenerator(function ($name) {
            return strtoupper(substr($name, 0, 1));
        });
    
  3. Event Listeners: Trigger events when avatars are generated/saved:

    // In EventServiceProvider
    Avatar::saved(function ($avatar) {
        \Log::info("Avatar saved: {$avatar->path}");
    });
    
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.
besmartand-pro/php-quality-config
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