File.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Casts\Attribute;
  4. use Illuminate\Database\Eloquent\Factories\HasFactory;
  5. use Illuminate\Database\Eloquent\Model;
  6. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  7. use Illuminate\Support\Facades\Storage;
  8. use Illuminate\Support\Str;
  9. class File extends Model
  10. {
  11. use HasFactory;
  12. protected $fillable = [
  13. 'user_id',
  14. 'original_name',
  15. 'mime_type',
  16. 'path',
  17. 'link',
  18. 'is_generated',
  19. ];
  20. protected $appends = [
  21. 'name',
  22. ];
  23. protected $casts = [
  24. 'is_generated' => 'boolean',
  25. ];
  26. public function user(): BelongsTo
  27. {
  28. return $this->belongsTo(User::class);
  29. }
  30. public function name(): Attribute
  31. {
  32. return Attribute::make(
  33. get: fn () => $this->original_name ?? '',
  34. );
  35. }
  36. public function thumbnailPath(): Attribute
  37. {
  38. return Attribute::make(
  39. get: function () {
  40. if (!$this->path || Str::contains(pathinfo($this->path, PATHINFO_FILENAME), '.thumbnail')) {
  41. return $this->path;
  42. }
  43. $directory = pathinfo($this->path, PATHINFO_DIRNAME);
  44. $filename = pathinfo($this->path, PATHINFO_FILENAME);
  45. $extension = pathinfo($this->path, PATHINFO_EXTENSION);
  46. $thumbnailName = $filename . '.thumbnail' . ($extension !== '' ? '.' . $extension : '');
  47. return $directory === '.' ? $thumbnailName : $directory . '/' . $thumbnailName;
  48. },
  49. );
  50. }
  51. public function thumbnailLink(): Attribute
  52. {
  53. return Attribute::make(
  54. get: function () {
  55. $thumbnailPath = $this->thumbnail_path;
  56. if ($thumbnailPath && Storage::disk('public')->exists($thumbnailPath)) {
  57. return url('/storage/' . $thumbnailPath);
  58. }
  59. return $this->link;
  60. },
  61. );
  62. }
  63. }