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.
Installation:
composer require creativeorange/gravatar
Publish the config file:
php artisan vendor:publish --provider="Creativeorange\Gravatar\GravatarServiceProvider"
Basic Usage:
{{ gravatar('user@example.com', '200') }}
use Creativeorange\Gravatar\Facades\Gravatar;
$url = Gravatar::get('user@example.com', 200);
First Use Case: Display a user's Gravatar in a profile view:
<img src="{{ gravatar(auth()->user()->email, '150') }}" alt="Profile">
config/gravatar.php – Define default sizes, ratings, and fallbacks.Creativeorange\Gravatar\Facades\Gravatar – Methods like get(), exists(), and setConfig().@gravatar for inline usage in views.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') }}
Dynamic Fallbacks: Override fallbacks per user or context:
Gravatar::setConfig(['default' => 'retro']);
$url = Gravatar::get('user@example.com');
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';
}
Caching: Leverage Laravel’s cache for performance:
Gravatar::setCacheDriver('redis');
Queueing for Bulk Processing: Process avatars asynchronously for high-traffic features:
Gravatar::queue()->get('user@example.com');
User Profile Avatars:
<img src="{{ gravatar($user->email, 'profile') }}" alt="{{ $user->name }}">
Comment Threads:
$comment->avatar = Gravatar::get($comment->user->email, 'comment');
Multi-Tenant SaaS:
Gravatar::setConfig(config("gravatar.profiles.{$tenant->plan}"));
API Responses:
return response()->json(['avatar' => Gravatar::get($user->email)]);
Gravatar::setHashing(function ($email) {
return hash('sha256', strtolower(trim($email)));
});
Gravatar::setHttpClient(new \GuzzleHttp\Client(['headers' => ['Authorization' => 'Bearer token']]));
Gravatar::listen(function ($email) {
Cache::forget("gravatar_{$email}");
});
Rate Limiting:
config/gravatar.php debug mode or external tools.Blade Directive Conflicts:
@gravatar('user@example.com', '200')
Or alias it in AppServiceProvider:
Blade::directive('userAvatar', function ($email) {
return "<?php echo Creativeorange\Gravatar\Facades\Gravatar::get($email); ?>";
});
Cache Invalidation:
Gravatar::clearCache('user@example.com');
SHA-256 Hashing:
Fallback Images:
mp, identicon, monsterid, wavatar, retro, robohash) may not suit all designs. Test custom fallbacks thoroughly.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());
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.
Custom Providers:
Extend the Creativeorange\Gravatar\Contracts\GravatarProvider interface to support non-Gravatar services.
Middleware: Scope Gravatar config per tenant or role:
Gravatar::setConfig(config("gravatar.profiles.{$request->tenant->plan}"));
Event System: Listen for Gravatar events (e.g., cache misses, API failures):
Gravatar::listen(function ($email, $event) {
// Handle event (e.g., log, retry)
});
Queue Jobs: Customize queue jobs for bulk processing:
Gravatar::queue()->get('user@example.com', ['size' => 200]);
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.
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.
How can I help you explore Laravel packages today?