creativeorange/gravatar
Laravel package for generating Gravatar URLs and image tags from email addresses. Configure size, default image, rating, and secure URLs, with helpers/facade for easy use in views and user profiles.
Installation
composer require creativeorange/gravatar
Publish the config file (optional but recommended for customization):
php artisan vendor:publish --provider="Creativeorange\Gravatar\GravatarServiceProvider" --tag="config"
First Use Case Generate a Gravatar URL in a controller or service:
use Creativeorange\Gravatar\Facades\Gravatar;
$avatarUrl = Gravatar::get('user@example.com');
Or directly in Blade templates:
<img src="{{ Gravatar::get('user@example.com') }}" alt="User Avatar">
Check Gravatar Existence Verify if a Gravatar exists for an email:
if (Gravatar::exists('user@example.com')) {
// Gravatar exists; proceed with logic
}
Blade Directive (Optional but Useful)
Register the directive in AppServiceProvider's boot() method:
use Illuminate\Support\Facades\Blade;
Blade::directive('gravatar', function ($expression) {
return "<?php echo Creativeorange\Gravatar\Facades\Gravatar::get($expression); ?>";
});
Usage in Blade:
@gravatar('user@example.com')
Define reusable avatar profiles in config/gravatar.php to standardize appearance across the app:
'profiles' => [
'profile' => [
'size' => 150,
'default' => 'identicon',
'rating' => 'pg',
],
'comment' => [
'size' => 50,
'default' => 'mp',
'rating' => 'g',
],
'team' => [
'size' => 80,
'default' => 'wavatar',
'rating' => 'pg',
],
],
Use profiles in code:
$profileUrl = Gravatar::get('user@example.com', 'profile');
$commentUrl = Gravatar::get('user@example.com', 'comment');
Override fallbacks per use case or user segment:
// Dynamic fallback for a specific user
$url = Gravatar::get('user@example.com', null, 'retro');
// Custom fallback URL (e.g., for premium users)
$url = Gravatar::get('premium@example.com', null, 'https://app.com/premium-avatar.png');
Leverage built-in caching to reduce API calls:
// Global cache (config/gravatar.php)
'cache' => [
'enabled' => true,
'ttl' => 86400, // 24 hours
],
// Per-request cache (override TTL)
$url = Gravatar::get('user@example.com', 'profile', null, 3600); // Cache for 1 hour
Use tenant-specific configurations or cache prefixes:
// Set tenant-specific cache prefix
$tenantId = Auth::user()->tenant_id;
Gravatar::setCacheKeyPrefix("tenant_{$tenantId}_");
// Generate tenant-scoped avatar
$url = Gravatar::get("user@tenant{$tenantId}.com", 'profile');
Extend functionality by listening to Gravatar events:
// Log Gravatar cache misses
Gravatar::addListener(function ($email, $size, $default, $rating) {
if (!Gravatar::exists($email)) {
Log::debug("Gravatar not found for {$email}; using fallback: {$default}");
}
});
Generate avatars for multiple users efficiently (e.g., for team pages or forums):
$users = User::where('role', 'team_member')->get();
$avatars = $users->mapWithKeys(function ($user) {
return [$user->email => Gravatar::get($user->email, 'team')];
});
Return Gravatar URLs in JSON APIs for consistency:
return response()->json([
'data' => [
'user' => [
'email' => 'user@example.com',
'avatar' => Gravatar::get('user@example.com', 'profile'),
],
],
]);
Validate email formats for Gravatar compatibility:
use Illuminate\Validation\Rule;
$validator = Validator::make($request->all(), [
'email' => [
'required',
'email',
Rule::exists('users', 'email')->ignore($user->id),
function ($attribute, $value, $fail) {
if (!Gravatar::exists($value)) {
$fail('The :attribute must be associated with a Gravatar account.');
}
},
],
]);
Ensure the @gravatar directive is registered globally in AppServiceProvider:
Blade::directive('gravatar', function ($expression) {
return "<?php echo Creativeorange\Gravatar\Facades\Gravatar::get($expression); ?>";
});
Usage in Blade:
<img src="@gravatar($user->email, 'profile')" alt="{{ $user->name }} Avatar">
Use responsive design with dynamic sizes:
<img
src="@gravatar($user->email, null, null, request()->wantsJson() ? 200 : 100)"
alt="{{ $user->name }} Avatar"
class="avatar"
style="width: {{ request()->wantsJson() ? '150px' : '75px' }};">
Apply fallbacks based on user roles or features:
$fallback = Auth::user()->isPremium() ? 'monsterid' : 'identicon';
$url = Gravatar::get('user@example.com', null, $fallback);
Mock Gravatar responses in unit/feature tests:
use Creativeorange\Gravatar\Facades\Gravatar;
Gravatar::shouldReceive('get')
->with('user@example.com', 'profile')
->andReturn('https://example.com/mock-avatar.jpg');
// Test in your test case
$response = $this->get('/profile');
$response->assertSee('https://example.com/mock-avatar.jpg');
Offload Gravatar URL generation to queues for performance:
// Dispatch a job to generate avatars
GenerateAvatarsJob::dispatch($userIds);
// In the job
public function handle() {
foreach ($this->userIds as $email) {
$url = Gravatar::get($email);
// Store or process $url
}
}
Hashing Migration (MD5 → SHA-256)
Gravatar::hash() to compare old/new hashes or pin to v1.0.24 for legacy systems.if (strlen(Gravatar::hash('user@example.com')) === 32) {
Log::warning('MD5 hash detected for user@example.com; upgrade to SHA-256.');
}
Rate Limiting
foreach ($emails as $email) {
$url = Gravatar::get($email);
sleep(1); // Throttle to 1 request/second
}
throttle middleware for API endpoints generating avatars.Fallback Conflicts
default parameters or use profile-based configs:
// Override config default for a specific case
$url = Gravatar::get($email, null, 'retro');
Blade Directive Scope
@gravatar directive may not work in nested Blade files if not globally registered.AppServiceProvider.Multi-Tenant Cache Collisions
Gravatar::setCacheKeyPrefix("tenant_{$
How can I help you explore Laravel packages today?