|
|
@@ -5,6 +5,8 @@
|
|
|
use App\Models\Student;
|
|
|
use App\Models\User;
|
|
|
use Illuminate\Database\Eloquent\Collection;
|
|
|
+use Illuminate\Http\UploadedFile;
|
|
|
+use Illuminate\Support\Facades\Storage;
|
|
|
|
|
|
class StudentService
|
|
|
{
|
|
|
@@ -25,6 +27,7 @@ public function findById(int $id): ?Student
|
|
|
public function create(User $user, array $data): Student
|
|
|
{
|
|
|
$unitId = $this->resolveUnitId($user);
|
|
|
+ $data = $this->handlePhoto($data);
|
|
|
|
|
|
return Student::create(array_merge($data, ['unit_id' => $unitId]));
|
|
|
}
|
|
|
@@ -37,6 +40,7 @@ public function update(int $id, array $data): ?Student
|
|
|
return null;
|
|
|
}
|
|
|
|
|
|
+ $data = $this->handlePhoto($data, $model->photo_url);
|
|
|
$model->update($data);
|
|
|
return $model->fresh();
|
|
|
}
|
|
|
@@ -49,9 +53,35 @@ public function delete(int $id): bool
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
+ if ($model->photo_url) {
|
|
|
+ Storage::delete($model->photo_url);
|
|
|
+ }
|
|
|
+
|
|
|
return $model->delete();
|
|
|
}
|
|
|
|
|
|
+ private function handlePhoto(array $data, ?string $oldPhotoPath = null): array
|
|
|
+ {
|
|
|
+ if (!isset($data['avatar'])) {
|
|
|
+ return $data;
|
|
|
+ }
|
|
|
+
|
|
|
+ if ($data['avatar'] instanceof UploadedFile) {
|
|
|
+ if ($oldPhotoPath) {
|
|
|
+ Storage::delete($oldPhotoPath);
|
|
|
+ }
|
|
|
+ $data['photo_url'] = $data['avatar']->store('students/photos');
|
|
|
+ } elseif (is_null($data['avatar'])) {
|
|
|
+ if ($oldPhotoPath) {
|
|
|
+ Storage::delete($oldPhotoPath);
|
|
|
+ }
|
|
|
+ $data['photo_url'] = null;
|
|
|
+ }
|
|
|
+
|
|
|
+ unset($data['avatar']);
|
|
|
+ return $data;
|
|
|
+ }
|
|
|
+
|
|
|
private function resolveUnitId(User $user): int
|
|
|
{
|
|
|
$unit = $user->units()->first();
|