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.
Installation:
composer require tomshaw/laravel-gravatar
No additional configuration is required—works out-of-the-box with Laravel 13+ and PHP 8.5.
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).
Where to Look First:
<img src="https://www.gravatar.com/..." /> with @gravatar().$user->email) for reuse in views.Dynamic Avatar Rendering: Use authenticated user emails in Blade:
<img src="@gravatar(email: auth()->user()->email, size: 80, default: 'identicon')">
$user->email or session data) to avoid hardcoding.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'))
config/app.php for global consistency.Conditional Avatars:
Show Gravatar only if the user has one (via forceDefault):
@gravatar(email: $user->email, forceDefault: 'y')
robohash) when Gravatar is unavailable.Secure Contexts:
Use secure: false for non-HTTPS environments (rare, but supported):
@gravatar(email: $user->email, secure: request()->isSecure())
Component Integration:
Create a reusable Blade component (resources/views/components/avatar.blade.php):
<img src="@gravatar(email: $email, size: $size ?? 60)" alt="{{ $alt ?? 'Avatar' }}">
<x-avatar email="user@example.com" size="100" />
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,
]));
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"');
Email Hashing: Gravatar uses MD5 hashes of emails. Ensure emails are exactly the same (case-sensitive) for consistent avatars.
strtolower($user->email)) before passing to @gravatar.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'.Secure Flag:
secure: true (default) forces HTTPS. If your app uses HTTP, set secure: false or configure Laravel to redirect HTTP to HTTPS.secure: true is used on HTTP pages.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).Blade Directive Scope:
@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]);
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
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.
Fallback Testing:
Test fallbacks by passing a non-existent email (e.g., nonexistent@example.com). Verify the default parameter renders correctly.
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); ?>";
});
}
<img src="@avatar($user->email)" />
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);
}
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',
],
Local Development: Mock Gravatar responses locally using a service like Vary or a local proxy to avoid hitting Gravatar’s CDN during development.
size: 60) where possible to reduce URL length and improve caching..jpg. For modern apps, consider using .webp via forceExtension: 'webp' (if supported by Gravatar).How can I help you explore Laravel packages today?