Installation:
composer require vigstudio/laravel-avatar
Publish the config (if needed):
php artisan vendor:publish --tag=avatar-config
Basic Usage: Generate an avatar from a string (e.g., name or email):
use Vigstudio\Avatar\Facades\Avatar;
$avatarUrl = Avatar::create('John Doe')->toUrl();
// Output: Gravatar-style URL (e.g., "https://www.gravatar.com/avatar/...")
First Use Case: Display a user’s avatar in a Blade template:
<img src="{{ Avatar::create(auth()->user()->name)->toUrl() }}" alt="Avatar">
Check config/avatar.php for:
Dynamic Avatar Generation: Use middleware or a trait to attach avatars to user models:
// In User model
public function avatarUrl()
{
return Avatar::create($this->name)->toUrl();
}
Local Storage Integration: Cache avatars locally for performance:
$avatar = Avatar::create('Jane Doe')
->setService('local')
->setPath(storage_path('app/avatars'))
->save();
Fallback Logic: Chain fallback methods for robustness:
$avatar = Avatar::create('A')
->fallback('initials')
->fallback('emoji')
->toUrl();
Blade Directives: Create a custom Blade directive for reuse:
// In AppServiceProvider
Blade::directive('avatar', function ($expression) {
return "<?php echo \\Vigstudio\\Avatar\\Facades\\Avatar::create({$expression})->toUrl(); ?>";
});
Usage:
<img src="{{ avatar($user->name) }}">
API Responses: Attach avatar URLs to JSON responses:
return User::find(1)->append('avatar_url');
(Requires adding avatar_url to $appends in the User model.)
Caching: Cache avatar URLs in Redis or the app cache to avoid regenerating:
$cacheKey = "avatar:{$user->email}";
$avatarUrl = Cache::remember($cacheKey, now()->addHours(1), function () use ($user) {
return Avatar::create($user->email)->toUrl();
});
Testing:
Mock the Avatar facade in tests:
$this->mock(\Vigstudio\Avatar\Facades\Avatar::class, function ($mock) {
$mock->shouldReceive('create')->andReturnSelf();
$mock->shouldReceive('toUrl')->andReturn('mock-avatar.jpg');
});
Gravatar Dependencies:
hash method works correctly (e.g., md5(strtolower(trim($email)))).Local Storage Permissions:
storage/app/avatars directory is writable:
chmod -R 755 storage/app/avatars
php artisan config:clear
Caching Issues:
$filename = md5($user->email).'.png';
Fallback Overrides:
initials) may conflict with existing methods. Check the source for available options.Log Avatar URLs: Temporarily log URLs to debug issues:
\Log::debug('Avatar URL', ['url' => Avatar::create('Test')->toUrl()]);
Validate Inputs: Sanitize inputs to avoid edge cases (e.g., empty strings, special characters):
$name = trim($user->name ?? '');
if (empty($name)) {
$name = 'Anonymous';
}
Custom Services: Extend the package by adding a new service provider:
// config/avatar.php
'services' => [
'custom' => \App\Services\CustomAvatarService::class,
],
Implement the Vigstudio\Avatar\Contracts\AvatarService interface.
Avatar Customization: Override the default avatar generator (e.g., for monogram avatars):
Avatar::create('John Doe')
->setService('local')
->setGenerator(function ($name) {
return strtoupper(substr($name, 0, 1));
});
Event Listeners: Trigger events when avatars are generated/saved:
// In EventServiceProvider
Avatar::saved(function ($avatar) {
\Log::info("Avatar saved: {$avatar->path}");
});
How can I help you explore Laravel packages today?