Last active
July 8, 2024 06:31
-
-
Save neverything/894db1c450934da319561cf21888dce2 to your computer and use it in GitHub Desktop.
Read the blog post: https://silvanhagen.com/writing/custom-driver-favicon-fetcher/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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