| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- <?php
- namespace App\Services;
- use App\Models\Event;
- use Illuminate\Database\Eloquent\Collection;
- use Illuminate\Http\UploadedFile;
- use Illuminate\Support\Facades\Storage;
- class EventService
- {
- public function __construct(protected MediaService $mediaService) {}
- public function getAll(): Collection
- {
- return Event::with('media')->orderBy('order')->orderBy('id')->get();
- }
- public function findById(int $id): ?Event
- {
- return Event::with('media')->find($id);
- }
- public function create(array $data): Event
- {
- if (!isset($data['order'])) {
- $data['order'] = Event::max('order') + 1;
- }
- $event = Event::create($data);
- return $event->load('media');
- }
- public function update(int $id, array $data): ?Event
- {
- $model = Event::find($id);
- if (!$model) {
- return null;
- }
- $model->update($data);
- return $model->fresh('media');
- }
- public function reorder(array $items): void
- {
- foreach ($items as $item) {
- Event::where('id', $item['id'])->update(['order' => $item['order']]);
- }
- }
- public function delete(int $id): bool
- {
- $model = Event::find($id);
- if (!$model) {
- return false;
- }
- if ($model->cover_path) {
- Storage::disk('s3')->delete($model->cover_path);
- }
- $model->media->each(fn($media) => $this->mediaService->delete($media->id));
- return $model->delete();
- }
- public function uploadCover(int $id, UploadedFile $file): ?Event
- {
- $model = Event::find($id);
- if (!$model) {
- return null;
- }
- if ($model->cover_path) {
- Storage::disk('s3')->delete($model->cover_path);
- }
- $model->cover_path = $file->store("events/{$id}/cover", 's3');
- $model->save();
- return $model->fresh('media');
- }
- public function removeCover(int $id): ?Event
- {
- $model = Event::find($id);
- if (!$model) {
- return null;
- }
- if ($model->cover_path) {
- Storage::disk('s3')->delete($model->cover_path);
- $model->cover_path = null;
- $model->save();
- }
- return $model->fresh('media');
- }
- }
|