-
-
Save mukundthanki/548ed8cd89440fd2f547523b3460743b to your computer and use it in GitHub Desktop.
This file contains hidden or 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\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