| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- <?php
- namespace App\Services;
- use App\Models\Student;
- use App\Models\StudentResponsible;
- use App\Models\User;
- use Illuminate\Database\Eloquent\Collection;
- use Illuminate\Http\UploadedFile;
- use Illuminate\Support\Facades\Storage;
- class StudentService
- {
- public function getAll(User $user): Collection
- {
- $unitId = $this->resolveUnitId($user);
- return Student::where('unit_id', $unitId)
- ->orderBy('created_at', 'desc')
- ->get();
- }
- public function findById(int $id): ?Student
- {
- return Student::find($id);
- }
- 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]));
- }
- public function update(int $id, array $data): ?Student
- {
- $model = $this->findById($id);
- if (!$model) {
- return null;
- }
- $responsibleData = $data['responsible'] ?? null;
- unset($data['responsible']);
- $data = $this->handlePhoto($data, $model->photo_url);
- $model->update($data);
- if ($responsibleData !== null) {
- StudentResponsible::updateOrCreate(
- ['student_id' => $id],
- array_merge($responsibleData, ['student_id' => $id]),
- );
- }
- return $model->fresh();
- }
- public function delete(int $id): bool
- {
- $model = $this->findById($id);
- if (!$model) {
- 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();
- abort_if(!$unit, 403, 'Usuário sem unidade associada.');
- return $unit->id;
- }
- }
|