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

Gravatar Laravel Package

creativeorange/gravatar

Laravel package for generating Gravatar URLs and image tags from email addresses. Configure size, default image, rating, and secure URLs, with helpers/facade for easy use in views and user profiles.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require creativeorange/gravatar
    

    Publish the config file (optional but recommended for customization):

    php artisan vendor:publish --provider="Creativeorange\Gravatar\GravatarServiceProvider" --tag="config"
    
  2. First Use Case Generate a Gravatar URL in a controller or service:

    use Creativeorange\Gravatar\Facades\Gravatar;
    
    $avatarUrl = Gravatar::get('user@example.com');
    

    Or directly in Blade templates:

    <img src="{{ Gravatar::get('user@example.com') }}" alt="User Avatar">
    
  3. Check Gravatar Existence Verify if a Gravatar exists for an email:

    if (Gravatar::exists('user@example.com')) {
        // Gravatar exists; proceed with logic
    }
    
  4. Blade Directive (Optional but Useful) Register the directive in AppServiceProvider's boot() method:

    use Illuminate\Support\Facades\Blade;
    
    Blade::directive('gravatar', function ($expression) {
        return "<?php echo Creativeorange\Gravatar\Facades\Gravatar::get($expression); ?>";
    });
    

    Usage in Blade:

    @gravatar('user@example.com')
    

Implementation Patterns

Core Workflows

1. Profile-Based Configuration

Define reusable avatar profiles in config/gravatar.php to standardize appearance across the app:

'profiles' => [
    'profile' => [
        'size' => 150,
        'default' => 'identicon',
        'rating' => 'pg',
    ],
    'comment' => [
        'size' => 50,
        'default' => 'mp',
        'rating' => 'g',
    ],
    'team' => [
        'size' => 80,
        'default' => 'wavatar',
        'rating' => 'pg',
    ],
],

Use profiles in code:

$profileUrl = Gravatar::get('user@example.com', 'profile');
$commentUrl = Gravatar::get('user@example.com', 'comment');

2. Dynamic Fallbacks

Override fallbacks per use case or user segment:

// Dynamic fallback for a specific user
$url = Gravatar::get('user@example.com', null, 'retro');

// Custom fallback URL (e.g., for premium users)
$url = Gravatar::get('premium@example.com', null, 'https://app.com/premium-avatar.png');

3. Caching Strategies

Leverage built-in caching to reduce API calls:

// Global cache (config/gravatar.php)
'cache' => [
    'enabled' => true,
    'ttl' => 86400, // 24 hours
],

// Per-request cache (override TTL)
$url = Gravatar::get('user@example.com', 'profile', null, 3600); // Cache for 1 hour

4. Multi-Tenant Support

Use tenant-specific configurations or cache prefixes:

// Set tenant-specific cache prefix
$tenantId = Auth::user()->tenant_id;
Gravatar::setCacheKeyPrefix("tenant_{$tenantId}_");

// Generate tenant-scoped avatar
$url = Gravatar::get("user@tenant{$tenantId}.com", 'profile');

5. Event-Driven Extensions

Extend functionality by listening to Gravatar events:

// Log Gravatar cache misses
Gravatar::addListener(function ($email, $size, $default, $rating) {
    if (!Gravatar::exists($email)) {
        Log::debug("Gravatar not found for {$email}; using fallback: {$default}");
    }
});

6. Bulk Processing

Generate avatars for multiple users efficiently (e.g., for team pages or forums):

$users = User::where('role', 'team_member')->get();
$avatars = $users->mapWithKeys(function ($user) {
    return [$user->email => Gravatar::get($user->email, 'team')];
});

7. API Responses

Return Gravatar URLs in JSON APIs for consistency:

return response()->json([
    'data' => [
        'user' => [
            'email' => 'user@example.com',
            'avatar' => Gravatar::get('user@example.com', 'profile'),
        ],
    ],
]);

8. Form Validation

Validate email formats for Gravatar compatibility:

use Illuminate\Validation\Rule;

$validator = Validator::make($request->all(), [
    'email' => [
        'required',
        'email',
        Rule::exists('users', 'email')->ignore($user->id),
        function ($attribute, $value, $fail) {
            if (!Gravatar::exists($value)) {
                $fail('The :attribute must be associated with a Gravatar account.');
            }
        },
    ],
]);

Integration Tips

Blade Integration

Ensure the @gravatar directive is registered globally in AppServiceProvider:

Blade::directive('gravatar', function ($expression) {
    return "<?php echo Creativeorange\Gravatar\Facades\Gravatar::get($expression); ?>";
});

Usage in Blade:

<img src="@gravatar($user->email, 'profile')" alt="{{ $user->name }} Avatar">

Dynamic Avatar Sizes

Use responsive design with dynamic sizes:

<img
    src="@gravatar($user->email, null, null, request()->wantsJson() ? 200 : 100)"
    alt="{{ $user->name }} Avatar"
    class="avatar"
    style="width: {{ request()->wantsJson() ? '150px' : '75px' }};">

Conditional Fallbacks

Apply fallbacks based on user roles or features:

$fallback = Auth::user()->isPremium() ? 'monsterid' : 'identicon';
$url = Gravatar::get('user@example.com', null, $fallback);

Testing

Mock Gravatar responses in unit/feature tests:

use Creativeorange\Gravatar\Facades\Gravatar;

Gravatar::shouldReceive('get')
    ->with('user@example.com', 'profile')
    ->andReturn('https://example.com/mock-avatar.jpg');

// Test in your test case
$response = $this->get('/profile');
$response->assertSee('https://example.com/mock-avatar.jpg');

Queue-Based Generation

Offload Gravatar URL generation to queues for performance:

// Dispatch a job to generate avatars
GenerateAvatarsJob::dispatch($userIds);

// In the job
public function handle() {
    foreach ($this->userIds as $email) {
        $url = Gravatar::get($email);
        // Store or process $url
    }
}

Gotchas and Tips

Pitfalls

  1. Hashing Migration (MD5 → SHA-256)

    • Issue: Upgrading from MD5 to SHA-256 (default in v1.0.25+) breaks cached URLs if not handled.
    • Fix: Use Gravatar::hash() to compare old/new hashes or pin to v1.0.24 for legacy systems.
    • Tip: Log deprecated MD5 hashes during transition:
      if (strlen(Gravatar::hash('user@example.com')) === 32) {
          Log::warning('MD5 hash detected for user@example.com; upgrade to SHA-256.');
      }
      
  2. Rate Limiting

    • Issue: Gravatar’s 1,000 requests/hour/IP limit can be hit during bulk operations (e.g., importing users).
    • Fix: Implement throttling or local caching:
      foreach ($emails as $email) {
          $url = Gravatar::get($email);
          sleep(1); // Throttle to 1 request/second
      }
      
    • Tip: Use Laravel’s throttle middleware for API endpoints generating avatars.
  3. Fallback Conflicts

    • Issue: Dynamic fallbacks may override config defaults unexpectedly.
    • Fix: Explicitly pass default parameters or use profile-based configs:
      // Override config default for a specific case
      $url = Gravatar::get($email, null, 'retro');
      
  4. Blade Directive Scope

    • Issue: @gravatar directive may not work in nested Blade files if not globally registered.
    • Fix: Use the facade explicitly or ensure the directive is registered in AppServiceProvider.
  5. Multi-Tenant Cache Collisions

    • Issue: Shared cache keys for multi-tenant avatars cause stale data.
    • Fix: Use tenant-aware cache keys:
      Gravatar::setCacheKeyPrefix("tenant_{$
      
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport