UnitMediaService.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace App\Services;
  3. use App\Models\UnitMedia;
  4. use Illuminate\Database\Eloquent\Collection;
  5. use Illuminate\Support\Facades\Storage;
  6. class UnitMediaService
  7. {
  8. public function getByUnitId(int $unitId): Collection
  9. {
  10. return UnitMedia::where('unit_id', $unitId)
  11. ->orderBy('created_at', 'desc')
  12. ->get();
  13. }
  14. public function getVisibleByUnitId(int $unitId): Collection
  15. {
  16. return UnitMedia::where('unit_id', $unitId)
  17. ->where('visible_to_franchisee', true)
  18. ->orderBy('created_at', 'desc')
  19. ->get();
  20. }
  21. //
  22. public function findById(int $id): ?UnitMedia
  23. {
  24. return UnitMedia::find($id);
  25. }
  26. public function create(array $data): UnitMedia
  27. {
  28. $file = $data['file'];
  29. $title = $data['title'];
  30. $fileUrl = $file->store('unit-media');
  31. $mimeType = $file->getMimeType();
  32. return UnitMedia::create([
  33. 'unit_id' => $data['unit_id'],
  34. 'title' => $title,
  35. 'file_url' => $fileUrl,
  36. 'mime_type' => $mimeType,
  37. 'visible_to_franchisee' => $data['visible_to_franchisee'] ?? false,
  38. ]);
  39. }
  40. public function update(int $id, array $data): ?UnitMedia
  41. {
  42. $model = $this->findById($id);
  43. if (!$model) {
  44. return null;
  45. }
  46. if (isset($data['file'])) {
  47. Storage::delete($model->file_url);
  48. $file = $data['file'];
  49. $data['file_url'] = $file->store('unit-media');
  50. $data['mime_type'] = $file->getMimeType();
  51. unset($data['file']);
  52. }
  53. $model->update($data);
  54. return $model->fresh();
  55. }
  56. public function delete(int $id): bool
  57. {
  58. $model = $this->findById($id);
  59. if (!$model) {
  60. return false;
  61. }
  62. Storage::delete($model->file_url);
  63. return $model->delete();
  64. }
  65. }