Skip to content

Instantly share code, notes, and snippets.

@neverything
Last active July 8, 2024 06:31
Show Gist options
  • Save neverything/894db1c450934da319561cf21888dce2 to your computer and use it in GitHub Desktop.
Save neverything/894db1c450934da319561cf21888dce2 to your computer and use it in GitHub Desktop.
<?php
namespace App\Models;
use AshAllenDesign\FaviconFetcher\Facades\Favicon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Storage;
class Creator extends Model
{
protected static function booted()
{
static::saving(function ($creator) {
$creator->fetchFavicon($creator->link);
});
}
public function fetchFavicon(?string $url): void
{
// If the link has not been changed and is not null, return early
if (! $this->isDirty('link') && $url !== null) {
return;
}
// If the avatar_url is set, delete the existing image
if ($this->avatar_url) {
Storage::disk('public')->delete($this->avatar_url);
$this->avatar_url = null;
}
// If the link is null, we're done
if ($url === null) {
return;
}
$favicon_path = Favicon::driver('unavatar-services')
->fetchOr($url, 'https://wireinthewild.com/favicon.png')
->store('avatars', 'public');
if ($favicon_path) {
$this->avatar_url = $favicon_path;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment