Upload.php 2.0 KB

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