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 an email or hash. Supports size, default image, rating, secure (HTTPS) URLs, and cache-busting options. Handy for quickly adding user avatars to your app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require creativeorange/gravatar
    

    Publish the config file:

    php artisan vendor:publish --provider="Creativeorange\Gravatar\GravatarServiceProvider"
    
  2. Basic Usage:

    • Blade Directive:
      {{ gravatar('user@example.com', '200') }}
      
    • Facade Method:
      use Creativeorange\Gravatar\Facades\Gravatar;
      $url = Gravatar::get('user@example.com', 200);
      
  3. First Use Case: Display a user's Gravatar in a profile view:

    <img src="{{ gravatar(auth()->user()->email, '150') }}" alt="Profile">
    

Where to Look First

  • Config File: config/gravatar.php – Define default sizes, ratings, and fallbacks.
  • Facade API: Creativeorange\Gravatar\Facades\Gravatar – Methods like get(), exists(), and setConfig().
  • Blade Directive: @gravatar for inline usage in views.

Implementation Patterns

Usage Patterns

  1. Config-Driven Profiles: Define reusable avatar profiles in config/gravatar.php:

    'profiles' => [
        'profile' => [
            'size' => 200,
            'default' => 'identicon',
            'rating' => 'pg',
        ],
        'comment' => [
            'size' => 50,
            'default' => 'mp',
            'rating' => 'g',
        ],
    ],
    

    Use in Blade:

    {{ gravatar('user@example.com', 'profile') }}
    
  2. Dynamic Fallbacks: Override fallbacks per user or context:

    Gravatar::setConfig(['default' => 'retro']);
    $url = Gravatar::get('user@example.com');
    
  3. Existence Checks: Verify if a Gravatar exists before rendering:

    if (Gravatar::exists('user@example.com')) {
        echo Gravatar::get('user@example.com');
    } else {
        echo 'No Gravatar found';
    }
    
  4. Caching: Leverage Laravel’s cache for performance:

    Gravatar::setCacheDriver('redis');
    
  5. Queueing for Bulk Processing: Process avatars asynchronously for high-traffic features:

    Gravatar::queue()->get('user@example.com');
    

Workflows

  1. User Profile Avatars:

    • Store user emails in the database.
    • Use Blade directives in profile views:
      <img src="{{ gravatar($user->email, 'profile') }}" alt="{{ $user->name }}">
      
  2. Comment Threads:

    • Cache Gravatar URLs for comments to reduce API calls:
      $comment->avatar = Gravatar::get($comment->user->email, 'comment');
      
  3. Multi-Tenant SaaS:

    • Scope config per tenant using middleware:
      Gravatar::setConfig(config("gravatar.profiles.{$tenant->plan}"));
      
  4. API Responses:

    • Return Gravatar URLs in JSON responses:
      return response()->json(['avatar' => Gravatar::get($user->email)]);
      

Integration Tips

  • Custom Hashing: Extend the package for non-Gravatar providers:
    Gravatar::setHashing(function ($email) {
        return hash('sha256', strtolower(trim($email)));
    });
    
  • HTTP Client: Replace the default client for custom headers:
    Gravatar::setHttpClient(new \GuzzleHttp\Client(['headers' => ['Authorization' => 'Bearer token']]));
    
  • Event Listeners: Trigger actions on Gravatar changes (e.g., cache invalidation):
    Gravatar::listen(function ($email) {
        Cache::forget("gravatar_{$email}");
    });
    

Gotchas and Tips

Pitfalls

  1. Rate Limiting:

    • Gravatar enforces 1,000 requests/hour/IP. Mitigate with caching and queueing.
    • Monitor usage via config/gravatar.php debug mode or external tools.
  2. Blade Directive Conflicts:

    • If using multiple packages with Blade directives, namespace the directive:
      @gravatar('user@example.com', '200')
      
      Or alias it in AppServiceProvider:
      Blade::directive('userAvatar', function ($email) {
          return "<?php echo Creativeorange\Gravatar\Facades\Gravatar::get($email); ?>";
      });
      
  3. Cache Invalidation:

    • Manual cache clearing is required for dynamic fallbacks:
      Gravatar::clearCache('user@example.com');
      
  4. SHA-256 Hashing:

    • The package uses SHA-256 by default (since v1.0.25). Ensure compatibility if overriding hashing logic.
  5. Fallback Images:

    • Gravatar’s default fallbacks (mp, identicon, monsterid, wavatar, retro, robohash) may not suit all designs. Test custom fallbacks thoroughly.

Debugging

  • Enable Debug Mode:

    'debug' => env('GRAVATAR_DEBUG', false),
    

    Logs Gravatar API requests and responses to storage/logs/gravatar.log.

  • Check Headers: Verify HTTP responses for errors (e.g., 404 for non-existent Gravatars):

    $response = Gravatar::getHttpClient()->get($url);
    if ($response->getStatusCode() !== 200) {
        // Handle error
    }
    
  • Test Locally: Use a mock HTTP client for testing:

    Gravatar::setHttpClient(new \Mockery\MockInterface());
    

Config Quirks

  • Profile Overrides: Profiles in config/gravatar.php are merged with method arguments. Later arguments override config values:

    Gravatar::get('user@example.com', ['size' => 100, 'default' => 'retro']);
    
  • Default Values: If no size is provided, the config’s default_size is used. Set it to null to enforce explicit sizes.

  • Rating Filter: Gravatar’s rating filters (g, pg, r, x) are case-sensitive. Use lowercase in config.

Extension Points

  1. Custom Providers: Extend the Creativeorange\Gravatar\Contracts\GravatarProvider interface to support non-Gravatar services.

  2. Middleware: Scope Gravatar config per tenant or role:

    Gravatar::setConfig(config("gravatar.profiles.{$request->tenant->plan}"));
    
  3. Event System: Listen for Gravatar events (e.g., cache misses, API failures):

    Gravatar::listen(function ($email, $event) {
        // Handle event (e.g., log, retry)
    });
    
  4. Queue Jobs: Customize queue jobs for bulk processing:

    Gravatar::queue()->get('user@example.com', ['size' => 200]);
    

Performance Tips

  • Cache Aggressively: Set a long TTL for static avatars (e.g., profile pictures):

    Gravatar::setCacheTTL(3600); // 1 hour
    
  • Use Queueing for Dynamic Avatars: Offload Gravatar generation for high-traffic features:

    Gravatar::queue()->get($email);
    
  • CDN Integration: Serve Gravatar URLs via a CDN to bypass rate limits and improve load times.

Security Considerations

  • Sanitize Emails: Gravatar uses emails for hashing. Sanitize input to avoid edge cases:

    $email = filter_var($request->email, FILTER_SANITIZE_EMAIL);
    
  • Rate Limit Monitoring: Track Gravatar API usage to avoid hitting rate limits. Consider a fallback to self-hosted avatars if limits are critical.

  • GDPR Compliance: If Gravatar’s data processing terms conflict with GDPR, evaluate self-hosted alternatives or disable Gravatar for EU users.

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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
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