meobda-website/app/Models/AuditionEtude.php

60 lines
1.5 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Storage;
class AuditionEtude extends Model
{
protected $fillable = [
'instrument_id', 'ensemble_id', 'set', 'original_filename', 'file_path', 'file_size',
];
protected static function booted(): void
{
static::deleting(function (AuditionEtude $etude) {
if ($etude->file_path) {
Storage::disk('public')->delete($etude->file_path);
}
});
}
public function instrument(): BelongsTo
{
return $this->belongsTo(Instrument::class);
}
public function ensemble(): BelongsTo
{
return $this->belongsTo(Ensemble::class);
}
public function getLinkToPDF()
{
return Storage::url($this->file_path);
}
protected function humanReadableFileSize(): Attribute
{
return Attribute::make(
get: function () {
$bytes = $this->file_size;
if ($bytes === null) {
return 'N/A';
}
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, 2).' '.$units[$pow];
}
);
}
}