Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Gravatarlib Laravel Package

thomaswelton/gravatarlib

A PHP library for working with Gravatar. Generate avatar URLs with configurable sizes, ratings, and default images, and fetch public profile data with a simple, framework-agnostic API that fits any PHP project, including Laravel.

View on GitHub
Deep Wiki
Context7

Getting Started

Install with Composer (the package is a maintained fork of emberlabs/gravatarlib, so the namespace is usually still emberlabs\GravatarLib):

composer require thomaswelton/gravatarlib

Look first at the Gravatar class in src/. The public surface is small: configure size, default image, max rating, and HTTPS, then call buildGravatarURL($email). Verify the exact method names against the installed version, since forks occasionally rename or add fluent variants.

Minimal first use — render an avatar URL in a controller or view:

use emberlabs\GravatarLib\Gravatar;

$gravatar = new Gravatar();
$gravatar->setAvatarSize(80);
$gravatar->setDefaultImage('identicon');
$gravatar->setMaxRating('pg');
$gravatar->enableHttps();

$url = $gravatar->buildGravatarURL($user->email);
<img src="{{ $url }}" alt="{{ $user->name }}" width="80" height="80">

The first real use case in a Laravel app is a reusable avatar URL/component for user models. The library only builds URLs — it does not fetch images, cache, or validate emails — so keep that in mind before designing around it.

Implementation Patterns

Wrap it in a small service. The underlying class is stateful; wrapping it prevents configuration leaking between call sites and gives you one place to handle empty emails and defaults.

namespace App\Services;

use emberlabs\GravatarLib\Gravatar;

final class GravatarService
{
    public function url(?string $email, int $size = 80, ?string $default = null, string $rating = 'pg'): string
    {
        $email = trim((string) $email);

        if ($email === '') {
            return $default ?? asset('images/avatar-placeholder.png');
        }

        $gravatar = new Gravatar();
        $gravatar->setAvatarSize($size);
        $gravatar->setDefaultImage($default ?? config('gravatar.default', 'identicon'));
        $gravatar->setMaxRating($rating);
        $gravatar->enableHttps();

        return $gravatar->buildGravatarURL($email);
    }
}

Bind it as a singleton only if it is stateless; otherwise let Laravel resolve it normally, or bind a factory. Avoid binding the raw Gravatar as a singleton because every call mutates shared configuration.

Config file (config/gravatar.php):

return [
    'size' => env('GRAVATAR_SIZE', 80),
    'default' => env('GRAVATAR_DEFAULT', 'identicon'),
    'rating' => env('GRAVATAR_RATING', 'pg'),
    'https' => true,
];

Model accessor for convenient use in views and API resources:

use Illuminate\Database\Eloquent\Casts\Attribute;

protected function avatarUrl(): Attribute
{
    return Attribute::get(fn () => app(\App\Services\GravatarService::class)
        ->url($this->email, size: 80));
}

Blade component:

namespace App\View\Components;

use App\Services\GravatarService;
use Illuminate\View\Component;

class Avatar extends Component
{
    public function __construct(
        public ?string $email = null,
        public int $size = 80,
        public ?string $name = null,
    ) {}

    public function url(): string
    {
        return app(GravatarService::class)->url($this->email, $this->size);
    }

    public function render()
    {
        return view('components.avatar');
    }
}
<img src="{{ $url() }}" alt="{{ $name }}" width="{{ $size }}" height="{{ $size }}" loading="lazy">

API resources — expose the URL rather than the email hash:

return [
    'id' => $this->id,
    'name' => $this->name,
    'avatar' => $this->avatar_url,
];

Front-end integration — because this is server-side URL generation only, pass the URL into Inertia/Livewire/Blade. If you need client-side size variants, either generate a few sizes server-side or replicate the hash/URL logic in JS; do not expect this package to help in the browser.

Testing — there is no HTTP call, so tests are pure string assertions. Assert the URL contains the expected SHA/MD5 hash, s=, d=, and r= parameters, and that https:// is used. For empty-email behavior, assert your placeholder is returned rather than a Gravatar URL.

Gotchas and Tips

  • Statefulness bites. setAvatarSize(), setDefaultImage(), etc. mutate the instance. A container singleton reused across requests/jobs with different sizes will produce surprising URLs. Create a fresh instance per URL, or encapsulate configuration in a service.
  • HTTPS is not automatic. If you do not call enableHttps() (or a fork equivalent), you can generate http:// URLs and get mixed-content warnings. Always enable it in production and assert it in tests.
  • Size is clamped. Classic gravatarlib enforces a min of 1 and a max of 512. Requesting a 1024px avatar silently gives you 512 unless the fork has lifted that limit. Check the constant before sizing hero images.
  • Email normalization matters. Gravatar hashes require trimming and lowercasing. If you pass a raw email with mixed case or whitespace, the hash will not match the user's registered avatar. Normalize before calling.
  • Hash algorithm. Older versions use MD5; Gravatar also supports SHA-256. MD5 still works but is deprecated in some contexts. If you need SHA-256 URLs, you may have to build them yourself or extend the class.
  • Default image values are special-cased. Values such as identicon, monsterid, wavatar, retro, robohash, blank, 404, and mm are passed through. If you supply a custom fallback URL, ensure it is URL-encoded; otherwise query strings in your fallback will corrupt the Gravatar URL.
  • Rating is advisory, not filtering. setMaxRating('pg') only affects which Gravatar image is served; it does not validate or filter anything in your app.
  • No HTTP, no cache, no validation. This package builds strings. It cannot tell you whether an avatar exists. If you need existence checks, use d=404 and perform an HTTP request yourself — and cache the result, because that is a network round trip.
  • Privacy/GDPR. Every rendered Gravatar URL causes the user's browser to request an external domain, leaking an email-derived hash. If that matters, proxy/cache avatars locally or fall back to local initials avatars by default.
  • Empty and invalid emails. Hashing an empty string returns a valid-looking URL with a default image. Decide explicitly whether you want that or a local placeholder; do not let it be accidental.
  • Caching the URL itself is usually unnecessary — generation is cheap and deterministic. Cache only if you add remote existence checks or proxy downloads. Invalidate on email change.
  • Extension points. Subclass Gravatar or decorate your service to override defaults, enforce a house rating, or swap in SHA-256 hashing. Keep custom logic in your wrapper rather than patching vendor code.
  • Fork provenance. The package is MIT-licensed and maintained, but it is a small community fork of an old PHP 5.3-era library. Check PHP 8 compatibility/deprecation notices in CI and pin a known-good version. If you hit limitations, generating the URL manually is only a few lines:
$hash = hash('sha256', strtolower(trim($email)));
$url = "https://www.gravatar.com/avatar/{$hash}?" . http_build_query([
    's' => 80,
    'd' => 'identicon',
    'r' => 'pg',
]);
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings
coleus/apps
seampact/laravel
emmyconceptng/laravel-ng-postcode
jjsquady/round-robin