| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- <?php
- namespace App\Services;
- use App\Models\StudentContract;
- use Carbon\Carbon;
- use Illuminate\Database\Eloquent\Collection;
- use Illuminate\Support\Facades\Storage;
- class StudentContractService
- {
- public function getAll(int $unitId, ?int $studentId = null): Collection
- {
- return StudentContract::where('unit_id', $unitId)
- ->when($studentId, fn ($q) => $q->where('student_id', $studentId))
- ->orderBy('created_at', 'desc')
- ->get();
- }
- public function findById(int $id): ?StudentContract
- {
- return StudentContract::find($id);
- }
- public function create(array $data): StudentContract
- {
- if (!empty($data['due_date'])) {
- $data['recurring_day'] = Carbon::parse($data['due_date'])->day;
- }
- return StudentContract::create($data);
- }
- public function update(int $id, array $data): ?StudentContract
- {
- $model = $this->findById($id);
- if (!$model) {
- return null;
- }
- if (!empty($data['due_date'])) {
- $data['recurring_day'] = Carbon::parse($data['due_date'])->day;
- }
- $model->update($data);
- return $model->fresh();
- }
- public function attachFile(int $id, $file): ?StudentContract
- {
- $model = $this->findById($id);
- if (!$model) {
- return null;
- }
- if ($model->file_url) {
- Storage::delete($model->file_url);
- }
- /** @var \Illuminate\Http\UploadedFile $file */
- $model->update([
- 'file_url' => $file->store('student-contracts'),
- 'file_type' => $file->getMimeType(),
- ]);
- return $model->fresh();
- }
- public function delete(int $id): bool
- {
- $model = $this->findById($id);
- if (!$model) {
- return false;
- }
- if ($model->file_url) {
- Storage::delete($model->file_url);
- }
- return $model->delete();
- }
- }
|