|
|
@@ -0,0 +1,92 @@
|
|
|
+<?php
|
|
|
+
|
|
|
+namespace App\Services;
|
|
|
+
|
|
|
+use App\Models\StudentMedia;
|
|
|
+use Illuminate\Database\Eloquent\Collection;
|
|
|
+use Illuminate\Support\Facades\Storage;
|
|
|
+
|
|
|
+class StudentMediaService
|
|
|
+{
|
|
|
+ public function getAll(array $filters = []): Collection
|
|
|
+ {
|
|
|
+ $query = StudentMedia::orderBy('created_at', 'desc');
|
|
|
+
|
|
|
+ if (!empty($filters['student_id'])) {
|
|
|
+ $query->where('student_id', $filters['student_id']);
|
|
|
+ }
|
|
|
+
|
|
|
+ if (!empty($filters['student_contract_id'])) {
|
|
|
+ $query->where('student_contract_id', $filters['student_contract_id']);
|
|
|
+ }
|
|
|
+
|
|
|
+ return $query->get();
|
|
|
+ }
|
|
|
+
|
|
|
+ public function create(array $data): StudentMedia
|
|
|
+ {
|
|
|
+ /** @var \Illuminate\Http\UploadedFile $file */
|
|
|
+ $file = $data['file'];
|
|
|
+ $path = $file->store('student-media');
|
|
|
+
|
|
|
+ return StudentMedia::create([
|
|
|
+ 'student_id' => $data['student_id'],
|
|
|
+ 'name' => $data['name'] ?? null,
|
|
|
+ 'url' => $path,
|
|
|
+ 'file_type' => $file->getMimeType(),
|
|
|
+ 'type' => 'media',
|
|
|
+ ]);
|
|
|
+ }
|
|
|
+
|
|
|
+ public function createFromContract(int $studentId, int $contractId, $file): StudentMedia
|
|
|
+ {
|
|
|
+ /** @var \Illuminate\Http\UploadedFile $file */
|
|
|
+ $path = $file->store('student-media');
|
|
|
+
|
|
|
+ return StudentMedia::create([
|
|
|
+ 'student_id' => $studentId,
|
|
|
+ 'student_contract_id' => $contractId,
|
|
|
+ 'url' => $path,
|
|
|
+ 'file_type' => $file->getMimeType(),
|
|
|
+ 'type' => 'contract',
|
|
|
+ ]);
|
|
|
+ }
|
|
|
+
|
|
|
+ public function findById(int $id): ?StudentMedia
|
|
|
+ {
|
|
|
+ return StudentMedia::find($id);
|
|
|
+ }
|
|
|
+
|
|
|
+ public function update(int $id, array $data): ?StudentMedia
|
|
|
+ {
|
|
|
+ $model = $this->findById($id);
|
|
|
+
|
|
|
+ if (!$model) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ if (isset($data['file'])) {
|
|
|
+ Storage::delete($model->url);
|
|
|
+ /** @var \Illuminate\Http\UploadedFile $file */
|
|
|
+ $file = $data['file'];
|
|
|
+ $data['url'] = $file->store('student-media');
|
|
|
+ $data['file_type'] = $file->getMimeType();
|
|
|
+ unset($data['file']);
|
|
|
+ }
|
|
|
+
|
|
|
+ $model->update($data);
|
|
|
+ return $model->fresh();
|
|
|
+ }
|
|
|
+
|
|
|
+ public function delete(int $id): bool
|
|
|
+ {
|
|
|
+ $model = $this->findById($id);
|
|
|
+
|
|
|
+ if (!$model) {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+
|
|
|
+ Storage::delete($model->url);
|
|
|
+ return $model->delete();
|
|
|
+ }
|
|
|
+}
|