store/app/Models/UserProfile.php

93 lines
2.4 KiB
PHP

<?php
namespace App\Models;
use App\Enums\Gender;
use App\Models\Concerns\HasModuleMedia;
use App\Models\Concerns\InteractsWithActivityLog;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Attributes\Appends;
use Illuminate\Database\Eloquent\Attributes\Guarded;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;
use Spatie\MediaLibrary\HasMedia;
#[Guarded(['id'])]
#[Appends(['birth_date_formatted', 'birth_date_input', 'gender_label', 'profile_photo_url'])]
class UserProfile extends Model implements HasMedia
{
// 1. Use Trait
use HasFactory, HasModuleMedia, InteractsWithActivityLog, SoftDeletes;
// 2. Casting
protected function casts(): array
{
return [
'birth_date' => 'date',
'gender' => Gender::class,
];
}
// 3. Attribute
public function birthDateFormatted(): Attribute
{
return Attribute::make(
get: fn () => $this->birth_date ? Carbon::parse($this->birth_date)->translatedFormat('l, d F Y') : '-',
);
}
public function birthDateInput(): Attribute
{
return Attribute::make(
get: fn () => $this->birth_date?->format('Y-m-d'),
);
}
public function genderLabel(): Attribute
{
return Attribute::make(
get: fn () => $this->gender?->label() ?? '-',
);
}
public function profilePhotoUrl(): Attribute
{
return Attribute::make(
get: function () {
$media = $this->getFirstMedia('profile_photo');
if (! $media) {
return null;
}
if ($media->disk === 's3') {
return Storage::disk('s3')->temporaryUrl($media->getPath(), now()->addMinutes(30));
}
return $media->getUrl();
},
);
}
// 4. Other Methods
public static function mediaModuleName(): string
{
return 'user-profile';
}
public function registerMediaCollections(): void
{
$this->addMediaCollection('profile_photo')->singleFile();
}
// 5. Relation
public function user(): BelongsTo
{
return $this->belongsTo(User::class)->withTrashed();
}
}