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

120 lines
2.8 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;
class Attachment extends Model
{
use HasFactory, SoftDeletes;
protected $fillable = [
'tenant_id',
'user_id',
'attachable_type',
'attachable_id',
'file_name',
'file_path',
'mime_type',
'file_size',
'category',
'description',
];
protected $casts = [
'file_size' => 'integer',
];
/**
* Get the parent attachable model.
*/
public function attachable()
{
return $this->morphTo();
}
/**
* Get the user who uploaded the attachment.
*/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* Get the tenant.
*/
public function tenant()
{
return $this->belongsTo(Tenant::class);
}
/**
* Get the public URL for the file.
*/
public function getUrlAttribute(): string
{
return Storage::url($this->file_path);
}
/**
* Get human-readable file size.
*/
public function getFormattedSizeAttribute(): string
{
$bytes = $this->file_size;
if ($bytes >= 1048576) {
return number_format($bytes / 1048576, 1) . ' MB';
}
if ($bytes >= 1024) {
return number_format($bytes / 1024, 1) . ' KB';
}
return $bytes . ' B';
}
/**
* Check if the file is an image.
*/
public function getIsImageAttribute(): bool
{
return str_starts_with($this->mime_type ?? '', 'image/');
}
/**
* Check if the file is a PDF.
*/
public function getIsPdfAttribute(): bool
{
return $this->mime_type === 'application/pdf';
}
/**
* Get the file icon based on mime type.
*/
public function getIconAttribute(): string
{
return match (true) {
$this->is_image => 'image',
$this->is_pdf => 'pdf',
str_contains($this->mime_type ?? '', 'word') || str_contains($this->mime_type ?? '', 'document') => 'doc',
str_contains($this->mime_type ?? '', 'sheet') || str_contains($this->mime_type ?? '', 'excel') => 'xls',
default => 'file',
};
}
/**
* Delete the file from storage when model is deleted.
*/
protected static function booted(): void
{
static::deleting(function (Attachment $attachment) {
if ($attachment->file_path && Storage::disk('public')->exists($attachment->file_path)) {
Storage::disk('public')->delete($attachment->file_path);
}
});
}
}