Upload.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. use zgldh\UploadManager\UploadManager;
  5. /**
  6. * Class Upload
  7. * @property string $name
  8. * @property string $description
  9. * @property string $disk
  10. * @property string $path
  11. * @property string $size
  12. * @property string $user_id
  13. * @package App
  14. */
  15. class Upload extends Model
  16. {
  17. protected $table = 'uploads';
  18. public function user()
  19. {
  20. return $this->belongsTo('App\User', 'user_id', 'id');
  21. }
  22. public function uploadable()
  23. {
  24. return $this->morphTo();
  25. }
  26. public function getUrlAttribute()
  27. {
  28. $manager = UploadManager::getInstance();
  29. $url = $manager->getUploadUrl($this->disk, $this->path);
  30. return $url;
  31. }
  32. public function deleteFile($autoSave = true)
  33. {
  34. if ($this->path) {
  35. $disk = \Storage::disk($this->disk);
  36. if ($disk->exists($this->path)) {
  37. $disk->delete($this->path);
  38. $this->path = '';
  39. if($autoSave)
  40. {
  41. $this->save();
  42. }
  43. }
  44. }
  45. }
  46. public function isInDisk($diskName)
  47. {
  48. return $this->disk == $diskName ? true : false;
  49. }
  50. public function moveToDisk($newDiskName)
  51. {
  52. if ($newDiskName == $this->disk) {
  53. return true;
  54. }
  55. $currentDisk = \Storage::disk($this->disk);
  56. $content = $currentDisk->get($this->path);
  57. $newDisk = \Storage::disk($newDiskName);
  58. $newDisk->put($this->path, $content);
  59. if ($newDisk->exists($this->path)) {
  60. $this->disk = $newDiskName;
  61. $this->save();
  62. $currentDisk->delete($this->path);
  63. return true;
  64. }
  65. return false;
  66. }
  67. }