| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- <?php
- namespace App\Models;
- 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\Support\Facades\Storage;
- use Illuminate\Support\Str;
- class File extends Model
- {
- use HasFactory;
- protected $fillable = [
- 'user_id',
- 'original_name',
- 'mime_type',
- 'path',
- 'link',
- 'is_generated',
- ];
- protected $appends = [
- 'name',
- ];
- protected $casts = [
- 'is_generated' => 'boolean',
- ];
- public function user(): BelongsTo
- {
- return $this->belongsTo(User::class);
- }
- public function name(): Attribute
- {
- return Attribute::make(
- get: fn () => $this->original_name ?? '',
- );
- }
- public function thumbnailPath(): Attribute
- {
- return Attribute::make(
- get: function () {
- if (!$this->path || Str::contains(pathinfo($this->path, PATHINFO_FILENAME), '.thumbnail')) {
- return $this->path;
- }
- $directory = pathinfo($this->path, PATHINFO_DIRNAME);
- $filename = pathinfo($this->path, PATHINFO_FILENAME);
- $extension = pathinfo($this->path, PATHINFO_EXTENSION);
- $thumbnailName = $filename . '.thumbnail' . ($extension !== '' ? '.' . $extension : '');
- return $directory === '.' ? $thumbnailName : $directory . '/' . $thumbnailName;
- },
- );
- }
- public function thumbnailLink(): Attribute
- {
- return Attribute::make(
- get: function () {
- $thumbnailPath = $this->thumbnail_path;
- if ($thumbnailPath && Storage::disk('public')->exists($thumbnailPath)) {
- return url('/storage/' . $thumbnailPath);
- }
- return $this->link;
- },
- );
- }
- }
|