CourseWork/app/Services/StudentService.php
2024-06-23 17:02:18 +04:00

86 lines
2.3 KiB
PHP

<?php
namespace App\Services;
use App\Enums\ScoreEnum;
use App\Models\Student;
use App\Models\Subject;
use App\Models\User;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Auth;
class StudentService
{
public function create(array $data): Student
{
$user = User::create([
'email' => $data['email'],
'password' => $data['password'],
]);
$student = Student::create([
'name' => $data['name'],
'last_name' => $data['last_name'],
'middle_name' => $data['middle_name'],
'birthday' => $data['birthday'],
'grade_id' => $data['grade_id'],
]);
$student->user()->save($user);
$student
->lessons()
->syncWithPivotValues($student->grade->lessons->pluck('id')->all(), ['score' => ScoreEnum::WithoutScore]);
return $student;
}
public function update(Student $student, array $data): Student
{
$student->user()->update([
'email' => $data['email'],
'password' => $data['password'],
]);
$student->update([
'name' => $data['name'],
'last_name' => $data['last_name'],
'middle_name' => $data['middle_name'],
'birthday' => $data['birthday'],
'grade_id' => $data['grade_id'],
]);
return $student;
}
public function delete($model): void
{
$model->user()->delete();
$model->delete();
}
public function getScores(Subject $subject): Collection
{
$student = Auth::user()->userable;
return $student->lessons()->where('subject_id', $subject->id)->get();
}
public function getAvgScore(Subject $subject)
{
$student = Auth::user()->userable;
$scores = $student
->lessons()
->where('subject_id', $subject->id)
->whereIn('score', ScoreEnum::getNumScores())
->pluck('score');
return round($scores->avg(), 2);
}
public function getDebts(): Collection
{
$student = Auth::user()->userable;
return $student->lessons()->whereIn('score', ScoreEnum::getDebtScores())->get();
}
}