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 package that adds a Blade @gravatar directive with named parameters. Generate Gravatar URLs from an email with options for size, default image style, and rating—perfect for quickly rendering user avatars in your views.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require tomshaw/laravel-gravatar
    

    No additional configuration is required—this package is zero-config.

  2. First Use Case: Insert a Gravatar into a Blade template for a user profile:

    <img src="@gravatar(email: $user->email, size: 80, default: 'identicon')" alt="User Avatar">
    

    This renders an 80px Gravatar with an identicon fallback if no Gravatar exists.

  3. Where to Look First:

    • Blade Templates: Use the @gravatar directive directly in views.
    • README: For parameter reference (e.g., rating, secure, forceDefault).
    • Source Code: GravatarDirective.php for advanced customization (if needed).

Implementation Patterns

Usage Patterns

  1. Dynamic User Avatars: Loop through users and render avatars with consistent sizing:

    @foreach($users as $user)
        <div class="user-card">
            <img src="@gravatar(email: $user->email, size: 50)" alt="{{ $user->name }}">
            <p>{{ $user->name }}</p>
        </div>
    @endforeach
    
  2. Conditional Fallbacks: Use default and rating to enforce brand guidelines:

    <img src="@gravatar(email: $user->email, default: 'retro', rating: 'pg')" alt="Profile">
    
    • rating: 'pg' ensures no explicit content.
    • default: 'retro' aligns with your design system.
  3. Secure URLs: Enable HTTPS for Gravatar URLs (default is secure: true):

    <img src="@gravatar(email: $user->email, secure: true)" alt="Secure Avatar">
    
  4. Component Integration: Create a reusable Blade component for avatars:

    @component('components.avatar', ['email' => $user->email, 'size' => 60])
        @slot('fallback')
            {{ strtoupper(substr($user->name, 0, 1)) }}
        @endslot
    @endcomponent
    

    Component File (resources/views/components/avatar.blade.php):

    <img
        src="@gravatar(email: $email, size: $size, default: 'identicon')"
        alt="{{ $slot ?? 'User Avatar' }}"
        class="avatar"
    >
    
  5. API Responses: Generate Gravatar URLs in JSON responses for frontend frameworks:

    return response()->json([
        'user' => [
            'avatar' => route('gravatar', [
                'email' => $user->email,
                'size'  => 100,
                'default' => 'wavatar'
            ]),
        ],
    ]);
    

    Route Definition (routes/web.php):

    Route::get('/gravatar', function (Request $request) {
        return Gravatar::getUrl($request->email, $request->size, $request->default);
    })->name('gravatar');
    

Workflows

  1. Team Onboarding:

    • Document the @gravatar directive in your team’s style guide.
    • Example snippet for new developers:
      <!-- Default avatar for comments -->
      <img src="@gravatar(email: $comment->user->email, size: 40)" alt="{{ $comment->user->name }}">
      
  2. A/B Testing: Test different default styles (e.g., retro vs. robohash) by toggling the default parameter in experiments:

    @if (config('app.feature_flag.robohash_avatars'))
        <img src="@gravatar(email: $user->email, default: 'robohash')">
    @else
        <img src="@gravatar(email: $user->email, default: 'retro')">
    @endif
    
  3. Caching: Cache Gravatar URLs in a service layer to reduce API calls (though Gravatar’s CDN is already optimized):

    class AvatarService {
        public function getCachedUrl(string $email, int $size = 60): string {
            $cacheKey = "gravatar_{$email}_{$size}";
            return cache()->remember($cacheKey, now()->addHours(1), function () use ($email, $size) {
                return Gravatar::getUrl($email, $size);
            });
        }
    }
    

Integration Tips

  1. Laravel Mix/Webpack: Use the directive in inline styles or JavaScript:

    <style>
        .user-avatar {
            background-image: url("@gravatar(email: '{{ $user->email }}', size: 30)");
        }
    </style>
    
  2. Livewire/Alpine.js: Dynamically update avatars when user data changes:

    <div x-data="{ email: '{{ $user->email }}' }">
        <img :src="'@gravatar(email: ' + email + ', size: 50)'" alt="Dynamic Avatar">
    </div>
    
  3. Testing: Mock Gravatar URLs in unit tests:

    use Tomshaw\Gravatar\Facades\Gravatar;
    
    public function test_gravatar_directive() {
        Gravatar::shouldReceive('getUrl')
                ->once()
                ->with('[email protected]', 60, 'mp')
                ->andReturn('https://example.com/avatar.jpg');
    
        $this->blade->render('@gravatar(email: "[email protected]", size: 60)')
                    ->assertSee('https://example.com/avatar.jpg');
    }
    

Gotchas and Tips

Pitfalls

  1. Email Validation:

    • Gravatar requires valid email hashes. Invalid emails (e.g., user@) will return a 404.
    • Fix: Sanitize emails before passing them to @gravatar:
      $email = filter_var($user->email, FILTER_SANITIZE_EMAIL);
      
  2. Size Limits:

    • The package enforces a 1–2048px range for $size. Passing 0 or 3000 will throw an exception.
    • Fix: Validate sizes in your application logic:
      $size = min(max($request->size, 1), 2048);
      
  3. Caching Headers:

    • Gravatar’s CDN caches responses aggressively. If you modify default or rating parameters, users may see stale images until the cache expires.
    • Fix: Use forceDefault: 'y' to bypass cache for testing:
      <img src="@gravatar(email: $user->email, default: 'robohash', forceDefault: 'y')">
      
  4. HTTPS Enforcement:

    • The secure parameter defaults to true, but some environments (e.g., local development) may ignore it.
    • Fix: Explicitly set secure: false for HTTP contexts:
      <img src="@gravatar(email: $user->email, secure: false)">
      
  5. Blade Compilation:

    • The @gravatar directive is compiled into a URL string. If you dynamically generate the directive (e.g., via JavaScript), it won’t work.
    • Fix: Generate URLs server-side and pass them to the frontend:
      // Controller
      $avatarUrl = Gravatar::getUrl($user->email, 60);
      return view('profile', compact('avatarUrl'));
      
      <!-- View -->
      <img src="{{ $avatarUrl }}" alt="User Avatar">
      

Debugging

  1. Invalid URLs:

    • If the Gravatar image doesn’t load, check the generated URL by inspecting the <img> tag’s src attribute.
    • Debugging Steps:
      1. Open browser dev tools (F12).
      2. Inspect the <img> tag and copy the src URL.
      3. Paste it into a browser to verify it works.
  2. Parameter Overrides:

    • Overriding parameters (e.g., rating: 'x') may fail if Gravatar’s API rejects them.
    • Fix: Validate against Gravatar’s supported parameters.
  3. Package Not Found:

    • If @gravatar is not recognized, ensure:
      • The package is installed (composer require tomshaw/laravel-gravatar).
      • Laravel’s service provider is auto-discovered (it is, since
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle