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

tomshaw/laravel-gravatar

Zero-config Laravel Blade @gravatar directive that generates Gravatar image URLs using named parameters. Pass email, size, default style, and rating to quickly render user avatars with sensible defaults and no setup.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require tomshaw/laravel-gravatar
    

    No additional configuration is required—works out-of-the-box with Laravel 13+ and PHP 8.5.

  2. First Use Case: Replace hardcoded Gravatar URLs in Blade templates with the @gravatar directive:

    <img src="@gravatar(email: 'user@example.com')" alt="User Avatar">
    

    This generates a 60px default (mp) Gravatar with rating: 'g' and secure: true (default values).

  3. Where to Look First:

    • Blade Templates: Replace <img src="https://www.gravatar.com/..." /> with @gravatar().
    • User Models: Cache the email property (e.g., $user->email) for reuse in views.
    • Documentation: Gravatar API Reference for parameter validation.

Implementation Patterns

Core Workflows

  1. Dynamic Avatar Rendering: Use authenticated user emails in Blade:

    <img src="@gravatar(email: auth()->user()->email, size: 80, default: 'identicon')">
    
    • Pattern: Pass dynamic values (e.g., from $user->email or session data) to avoid hardcoding.
  2. Consistent Fallbacks: Standardize defaults across the app (e.g., default: 'retro' for all user avatars):

    @gravatar(email: $comment->user->email, default: config('app.avatar_fallback'))
    
    • Tip: Define defaults in config/app.php for global consistency.
  3. Conditional Avatars: Show Gravatar only if the user has one (via forceDefault):

    @gravatar(email: $user->email, forceDefault: 'y')
    
    • Use Case: Force a fallback (e.g., robohash) when Gravatar is unavailable.
  4. Secure Contexts: Use secure: false for non-HTTPS environments (rare, but supported):

    @gravatar(email: $user->email, secure: request()->isSecure())
    
  5. Component Integration: Create a reusable Blade component (resources/views/components/avatar.blade.php):

    <img src="@gravatar(email: $email, size: $size ?? 60)" alt="{{ $alt ?? 'Avatar' }}">
    
    • Usage:
      <x-avatar email="user@example.com" size="100" />
      

Integration Tips

  • Validation: Validate email formats before passing to @gravatar (e.g., using Laravel’s ValidatesEmail).

  • Caching: Cache Gravatar URLs in Redis if rendering avatars frequently (e.g., in comment loops):

    $cacheKey = "gravatar:{$user->email}:{$size}:{$default}";
    $url = Cache::remember($cacheKey, now()->addHours(1), fn() => route('gravatar', [
        'email' => $user->email,
        'size' => $size,
        'default' => $default,
    ]));
    
    • Note: This requires a custom route; the package itself doesn’t cache.
  • Testing: Mock Gravatar responses in PHPUnit:

    $this->get('/')->assertSee('<img src="https://www.gravatar.com/avatar/'.md5('test@example.com').'?s=60&d=mp&r=pg"');
    

Gotchas and Tips

Pitfalls

  1. Email Hashing: Gravatar uses MD5 hashes of emails. Ensure emails are exactly the same (case-sensitive) for consistent avatars.

    • Fix: Normalize emails (e.g., strtolower($user->email)) before passing to @gravatar.
  2. Parameter Validation:

    • size must be between 1 and 2048 (inclusive). Omitting or setting invalid values defaults to 60.
    • rating must be one of ['g', 'pg', 'r', 'x']. Invalid values default to 'g'.
    • Debugging: Check the generated URL in the browser’s "Inspect Element" to verify parameters.
  3. Secure Flag:

    • secure: true (default) forces HTTPS. If your app uses HTTP, set secure: false or configure Laravel to redirect HTTP to HTTPS.
    • Warning: Mixed-content warnings may appear in browsers if secure: true is used on HTTP pages.
  4. Force Defaults:

    • forceDefault: 'y' bypasses Gravatar’s checks and always shows the default image. Use sparingly (e.g., for testing or when Gravatar is unreliable).
  5. Blade Directive Scope:

    • The @gravatar directive only works in Blade templates. For non-Blade contexts (e.g., API responses), use the underlying Gravatar facade:
      use Tomshaw\Gravatar\Facades\Gravatar;
      $url = Gravatar::get('user@example.com', ['size' => 80]);
      

Debugging Tips

  1. Generated URLs: Log the raw Gravatar URL to debug issues:

    @php
        $url = \Tomshaw\Gravatar\Facades\Gravatar::get('user@example.com', [
            'size' => 60,
            'default' => 'identicon'
        ]);
        \Log::debug('Gravatar URL:', [$url]);
    @endphp
    
  2. CORS Issues: If Gravatar images fail to load, ensure your app’s CORS policy allows requests to gravatar.com. This is rare but can occur in iframes or SPAs.

  3. Fallback Testing: Test fallbacks by passing a non-existent email (e.g., nonexistent@example.com). Verify the default parameter renders correctly.

Extension Points

  1. Custom Directives: Extend the package by creating a new Blade directive (e.g., @avatar with additional logic):

    // app/Providers/BladeServiceProvider.php
    public function boot(): void
    {
        Blade::directive('avatar', function ($expression) {
            return "<?php echo \\Tomshaw\\Gravatar\\Facades\\Gravatar::get($expression); ?>";
        });
    }
    
    • Usage:
      <img src="@avatar($user->email)" />
      
  2. Middleware: Add Gravatar-specific middleware to validate emails or enforce defaults:

    public function handle(Request $request, Closure $next)
    {
        if ($request->has('gravatar_email')) {
            $request->merge(['gravatar_email' => strtolower($request->gravatar_email)]);
        }
        return $next($request);
    }
    
  3. Configuration: Override defaults in config/services.php (if the package supports it) or use a service provider:

    // config/gravatar.php (if added by the package)
    'defaults' => [
        'size' => 80,
        'default' => 'retro',
        'rating' => 'pg',
    ],
    
  4. Local Development: Mock Gravatar responses locally using a service like Vary or a local proxy to avoid hitting Gravatar’s CDN during development.

Performance Considerations

  • Avoid Dynamic Parameters: Hardcode static parameters (e.g., size: 60) where possible to reduce URL length and improve caching.
  • CDN Leverage: Gravatar’s CDN is optimized for performance. Avoid reinventing caching layers unless you have specific needs (e.g., A/B testing).
  • Image Formats: The package defaults to .jpg. For modern apps, consider using .webp via forceExtension: 'webp' (if supported by Gravatar).
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui