trypost/app/Models/Media.php

99 lines
2.3 KiB
PHP
Raw Permalink Normal View History

2026-01-15 01:13:44 +00:00
<?php
declare(strict_types=1);
2026-01-15 01:13:44 +00:00
namespace App\Models;
use App\Enums\Media\Type as MediaType;
use Database\Factories\MediaFactory;
2026-01-15 01:13:44 +00:00
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
2026-01-15 01:13:44 +00:00
use Illuminate\Support\Facades\Storage;
class Media extends Model
2026-01-15 01:13:44 +00:00
{
/** @use HasFactory<MediaFactory> */
2026-01-15 01:13:44 +00:00
use HasFactory, HasUuids;
protected $table = 'medias';
2026-01-15 17:24:39 +00:00
protected $appends = ['url'];
2026-01-15 01:13:44 +00:00
protected $fillable = [
'mediable_id',
'mediable_type',
2026-01-21 20:57:15 +00:00
'group_id',
'collection',
2026-01-15 01:13:44 +00:00
'type',
'path',
'original_filename',
'mime_type',
'size',
'order',
'meta',
'upload_token',
2026-01-15 01:13:44 +00:00
];
protected function casts(): array
{
return [
'type' => MediaType::class,
'size' => 'integer',
'order' => 'integer',
'meta' => 'array',
];
}
public function mediable(): MorphTo
2026-01-15 01:13:44 +00:00
{
return $this->morphTo();
2026-01-15 01:13:44 +00:00
}
protected function url(): Attribute
{
return Attribute::make(
2026-01-15 17:24:39 +00:00
get: fn () => Storage::url($this->path),
2026-01-15 01:13:44 +00:00
);
}
public function isVideo(): bool
{
return MediaType::classify($this->mime_type, $this->path) === MediaType::Video;
}
public function isImage(): bool
{
return MediaType::classify($this->mime_type, $this->path) === MediaType::Image;
}
public function isDocument(): bool
{
return MediaType::classify($this->mime_type, $this->path) === MediaType::Document;
}
2026-01-15 01:13:44 +00:00
public function getTemporaryUrl(int $expirationMinutes = 60): string
{
2026-01-15 17:24:39 +00:00
return Storage::temporaryUrl(
2026-01-15 01:13:44 +00:00
$this->path,
now()->addMinutes($expirationMinutes)
);
}
public function delete(): bool
{
2026-01-21 20:57:15 +00:00
// Only delete the file if no other media records use the same path
$otherMediaWithSamePath = static::where('path', $this->path)
->where('id', '!=', $this->id)
->exists();
if (! $otherMediaWithSamePath) {
Storage::delete($this->path);
}
2026-01-15 01:13:44 +00:00
return parent::delete();
}
}