vernova/app/Models/LetterAttachment.php
2026-07-26 19:58:27 +03:30

84 lines
1.7 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
class LetterAttachment extends Model
{
use HasFactory;
public const UPDATED_AT = null;
protected $fillable = [
'letter_id',
'file_name',
'file_path',
'file_size',
'mime_type',
'created_at',
];
protected $casts = [
'file_size' => 'integer',
];
public function letter()
{
return $this->belongsTo(Letter::class);
}
/**
* Get the URL for the attachment.
*/
public function getUrlAttribute(): string
{
return Storage::disk('public')->url($this->file_path);
}
/**
* Check if the attachment is an image.
*/
public function getIsImageAttribute(): bool
{
return str_starts_with($this->mime_type ?? '', 'image/');
}
/**
* Check if the attachment is a PDF.
*/
public function getIsPdfAttribute(): bool
{
return ($this->mime_type ?? '') === 'application/pdf';
}
/**
* Get the formatted file size.
*/
public function getFormattedSizeAttribute(): string
{
$bytes = $this->file_size ?? 0;
if ($bytes >= 1048576) {
return round($bytes / 1048576, 1) . ' MB';
}
if ($bytes >= 1024) {
return round($bytes / 1024, 1) . ' KB';
}
return $bytes . ' B';
}
protected static function booted()
{
static::creating(function ($attachment) {
if (empty($attachment->created_at)) {
$attachment->created_at = now();
}
});
}
}