Installation:
composer require martian/laravatar
Publish the config file (optional):
php artisan vendor:publish --provider="Martian\Laravatar\LaravatarServiceProvider" --tag="config"
Configure Default Driver:
Edit config/laravatar.php to set your preferred driver (e.g., dicebear):
'driver' => env('LARAVATAR_DRIVER', 'dicebear'),
First Use Case:
Generate an avatar for a model (e.g., User):
use Martian\Laravatar\Facades\Laravatar;
$avatarUrl = Laravatar::generate('john.doe@example.com'); // Gravatar email
// OR for DiceBear:
$avatarUrl = Laravatar::generate('john.doe', 'dicebear');
Model Integration:
Add an accessor to your User model:
public function getAvatarAttribute()
{
return Laravatar::generate($this->email);
}
Now use $user->avatar in Blade or controllers.
Driver-Specific Generation:
https://s.gravatar.com/avatar/{md5}/?d=mp).
Laravatar::generate('user@example.com', 'gravatar');
Laravatar::generate('john.doe', 'dicebear', [
'style' => 'pixel-art',
'backgroundColor' => '#f0f0f0',
]);
Dynamic Avatar URLs: Cache URLs in a model trait or service to avoid regenerated requests:
// app/Services/AvatarService.php
public function getCachedAvatar($model, $driver = null)
{
return $model->avatar ?? $model->update(['avatar' => Laravatar::generate($model->email, $driver)])->avatar;
}
Blade Directives: Create a custom Blade directive for reusable avatar tags:
// app/Providers/BladeServiceProvider.php
Blade::directive('avatar', function ($expression) {
return "<?php echo app('laravatar')->generate({$expression}); ?>";
});
Usage:
<img src="{{ avatar($user->email) }}" alt="Avatar">
API Responses:
Attach avatars to API responses via AppServiceProvider:
public function boot()
{
Response::macro('withAvatar', function ($model, $driver = null) {
return $this->with('avatar', Laravatar::generate($model->email, $driver));
});
}
Usage:
return response()->withAvatar($user)->json($user->toArray());
Queueing Heavy Generations: Offload avatar generation to a queue (e.g., for DiceBear API calls):
// Dispatch a job
GenerateAvatarJob::dispatch($user->email, 'dicebear', $options);
// Job class
public function handle()
{
$this->user->update(['avatar' => Laravatar::generate($this->email, $this->driver, $this->options)]);
}
Gravatar Fallbacks:
'gravatar' => [
'fallback' => 'https://via.placeholder.com/200?text=No+Avatar',
],
DiceBear/API Rate Limits:
$avatar = Cache::remember("avatar_{$user->email}", now()->addHours(1), function () {
return Laravatar::generate($user->email, 'dicebear');
});
CORS Issues:
config/cors.php:
'paths' => ['api/*', 'avatars/*'], // Include avatar routes
SVG vs. PNG:
$svgUrl = Laravatar::generate('user', 'boring-avatar');
$pngUrl = str_replace('.svg', '.png', $svgUrl); // Manual conversion (consider using a library like `spatie/image-optimizer`)
Model Observers:
creating/updating observers if the driver is external (e.g., DiceBear). Use a queue job instead to prevent timeouts.Driver-Specific Errors:
laravatar.log (configured in config/laravatar.php) for driver-specific failures.[2023-10-01 12:00:00] laravatar.ERROR: DiceBear API returned 429 (Too Many Requests)
URL Validation:
$avatarUrl = Laravatar::generate('test');
if (!filter_var($avatarUrl, FILTER_VALIDATE_URL)) {
throw new \Exception("Invalid avatar URL generated");
}
Custom Drivers:
Create a new driver by extending Martian\Laravatar\Contracts\Driver:
namespace App\Providers;
use Martian\Laravatar\Contracts\Driver;
class CustomDriver implements Driver
{
public function generate($seed, array $options = [])
{
// Your logic here (e.g., call an internal API)
return "https://your-api.com/avatar?seed={$seed}";
}
}
Register it in config/laravatar.php:
'drivers' => [
'custom' => \App\Providers\CustomDriver::class,
],
Middleware for Avatar Generation: Add middleware to generate avatars for anonymous users:
// app/Http/Middleware/GenerateGuestAvatar.php
public function handle($request, Closure $next)
{
if (auth()->guest() && !$request->user()->avatar) {
$request->user()->update(['avatar' => Laravatar::generate($request->user()->email)]);
}
return $next($request);
}
Dynamic Driver Selection: Use a model trait to dynamically select drivers based on user roles:
// app/Models/User.php
public function getAvatarDriver()
{
return $this->isPremium ? 'dicebear' : 'gravatar';
}
public function getAvatarAttribute()
{
return Laravatar::generate($this->email, $this->getAvatarDriver());
}
Testing:
Mock the Laravatar facade in tests:
Laravatar::shouldReceive('generate')
->once()
->with('test@example.com', 'gravatar')
->andReturn('https://test-avatar.com');
How can I help you explore Laravel packages today?