laravolt/avatar
Generate unique user avatars from names or emails (initials-based) for Laravel and PHP. Output as base64 data URI, save as PNG/JPG, or fall back to Gravatar. Easy install, configurable, supports Laravel, Lumen, and non-Laravel projects.
## Getting Started
### Minimal Setup
1. **Installation**:
```bash
composer require laravolt/avatar
(Laravel 5.5+ auto-discovers the package; for older versions, register Laravolt\Avatar\ServiceProvider in config/app.php and add the facade alias.)
First Use Case: Generate an avatar from a name in a Blade view:
<img src="{{ Avatar::create('John Doe')->toBase64() }}" alt="Avatar">
This outputs a data-URI (base64-encoded image) directly usable in HTML.
Key Files:
config/laravolt/avatar.php (published via php artisan vendor:publish --provider="Laravolt\Avatar\ServiceProvider").Dynamic Avatar Generation:
// In a controller or service
$avatarUrl = Avatar::create($user->name)
->setDimension(80, 80)
->setBackground('#3498db')
->toBase64();
return response()->json(['avatar' => $avatarUrl]);
Theming for Consistency:
Apply predefined themes (e.g., grayscale-light) or customize runtime:
Avatar::create('Alice Smith')
->setTheme('colorful') // Uses predefined theme
->toSvg();
Or override specific attributes:
Avatar::create('Bob Johnson')
->setChars(1) // Single initial
->setFontSize(36)
->toBase64();
Gravatar Fallback: For users with email-based avatars (e.g., Gravatar):
$gravatarUrl = Avatar::create($user->email)->toGravatar(['d' => 'retro']);
SVG for Scalability: Use SVG for resolution-independent avatars (e.g., in icons or responsive designs):
<div class="avatar-container">
{!! Avatar::create('Eve Adams')->setResponsive()->toSvg() !!}
</div>
File Storage: Save avatars to disk for reuse (e.g., in user profiles):
$path = storage_path('app/avatars/' . $user->id . '.png');
Avatar::create($user->name)->save($path);
Blade Directives: Create a custom Blade directive for reusable avatar generation:
// In AppServiceProvider@boot()
Blade::directive('avatar', function ($expression) {
return "<?php echo Laravolt\Avatar\Facade::create($expression)->toBase64(); ?>";
});
Usage:
<img src="{{ avatar($user->name) }}" alt="User Avatar">
Caching: Cache generated avatars to reduce server load (Laravel 10+):
$avatar = Cache::remember("avatar_{$user->id}", now()->addHours(1), function () use ($user) {
return Avatar::create($user->name)->toBase64();
});
Intervention Image Extensions:
Leverage the underlying Intervention\Image object for advanced manipulations:
$image = Avatar::create('Charlie Brown')->getImageObject();
$image->resize(50, 50)->save(storage_path('app/avatars/thumbs/charlie.png'));
API Responses: Return avatars as base64 in API responses:
return response()->json([
'avatar' => Avatar::create($user->name)->toBase64()
]);
Non-ASCII Handling:
Enable ASCII conversion in config/laravolt/avatar.php for non-Latin names:
'ascii' => true,
Font Support:
ñ, ü) may render incorrectly if the font lacks glyphs.'ascii' => true in config or use a font like Noto Sans (supports Unicode).Image Driver Conflicts:
gd is selected but not installed, avatars fail silently.php-gd is installed or switch to imagick in config.SVG Caching:
{!! Avatar::create($user->name)->setResponsive()->toSvg() !!}
<script>
document.querySelector('svg').setAttribute('data-version', '{{ md5(filemtime(public_path('index.php'))) }}');
</script>
Gravatar Hashing:
Avatar::create('user@example.com')->toGravatar(['default' => 'mp'], true); // Force MD5
Border Radius in SVG:
border.radius config only affects SVG avatars. PNG/JPG avatars ignore it.setBorder(1, '#000', 10) at runtime for SVG-specific adjustments.Inspect Generated Config: Dump the active config to debug overrides:
dd(Avatar::create('Test')->getAttribute('backgrounds'));
Check Intervention Image: If avatars appear corrupted, verify Intervention Image is working:
use Intervention\Image\Facades\Image;
Image::make(public_path('test.png'))->resize(100, 100)->save(public_path('test-resized.png'));
Font Paths:
Absolute paths in fonts config are required. Relative paths fail:
'fonts' => [base_path('fonts/OpenSans-Bold.ttf')], // Correct
'fonts' => ['fonts/OpenSans-Bold.ttf'], // Fails
Base64 Encoding: Large avatars (>100KB) may cause performance issues or fail in some browsers.
Laravel Caching: Clear config cache after publishing updates:
php artisan config:clear
Custom Generators:
Extend the DefaultGenerator to implement custom logic (e.g., emoji-based avatars):
class EmojiGenerator extends \Laravolt\Avatar\Generator\DefaultGenerator {
public function generate($name) {
return mb_substr($name, 0, 1) === 'A' ? '🍎' : parent::generate($name);
}
}
Register in config/laravolt/avatar.php:
'generator' => \App\Generators\EmojiGenerator::class,
Dynamic Themes: Fetch themes from a database or API:
$theme = Theme::where('user_id', $user->id)->first()->toArray();
Avatar::create($user->name)->setTheme($theme)->toSvg();
Storage Adapters: Integrate with cloud storage (e.g., S3) for saved avatars:
use League\Flysystem\Filesystem;
$fs = new Filesystem(/* ... */);
Avatar::create($user->name)->saveTo($fs, 'avatars/' . $user->id . '.png');
Blade Components: Create a reusable component:
// app/View/Components/Avatar.php
public function render() {
return <<<html
<img src="{$this->avatar->toBase64()}" alt="{$this->name}">
html;
}
Usage:
<x-avatar :avatar="Avatar::create($user->name)" :name="$user->name" />
Testing:
Mock the Avatar facade in tests:
Avatar::shouldReceive('create')
->with('Test User')
->andReturn(FakeAvatar::make());
Use a fake implementation for consistent test outputs.
---
How can I help you explore Laravel packages today?