Skip to content

Instantly share code, notes, and snippets.

@newtonjob
Last active April 12, 2025 11:41
Show Gist options
  • Save newtonjob/f415b55ef8312c9f621b6e7c7d7bfc0c to your computer and use it in GitHub Desktop.
Save newtonjob/f415b55ef8312c9f621b6e7c7d7bfc0c to your computer and use it in GitHub Desktop.
<?php
namespace App\Models\Concerns;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Uri;
trait HasPhoto
{
public function photo(): Attribute
{
return Attribute::set(fn ($value) => $value instanceof UploadedFile
? $value->store(config('folders.avatars'))
: $value
)->withoutObjectCaching();
}
public function photoUrl(): Attribute
{
return Attribute::get(function (): string {
if ($this->photo) {
return Storage::cdn(
path: $this->photo,
transformations: 'h_300,w_300,c_fill,g_face,r_20',
);
}
$colors = [
['text' => '7239EA', 'bg' => 'F8F5FF'],
['text' => 'F1416C', 'bg' => 'FFF5F8'],
['text' => 'FFC700', 'bg' => 'FFF8DD'],
['text' => '3E97FF', 'bg' => 'EEF6FF'],
['text' => '50CD89', 'bg' => 'E8FFF3'],
];
$color = $colors[crc32($this->name) % count($colors)];
return Uri::of('https://ui-avatars.com/api/photo.jpg')->withQuery([
'background' => $color['bg'],
'color' => $color['text'],
'name' => (string) $this->name,
'size' => 220,
'format' => 'jpg',
]);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment