From 3ef579d5eddde40406c47034e77ea0b94c5fd3f1 Mon Sep 17 00:00:00 2001 From: Matt Young Date: Thu, 30 May 2024 19:35:30 -0500 Subject: [PATCH] Creating student works. Need to work on validation rules --- app/Http/Controllers/StudentController.php | 4 +- app/Rules/UniqueFullNameAtSchool.php | 43 ++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 app/Rules/UniqueFullNameAtSchool.php diff --git a/app/Http/Controllers/StudentController.php b/app/Http/Controllers/StudentController.php index a48482a..2ff5850 100644 --- a/app/Http/Controllers/StudentController.php +++ b/app/Http/Controllers/StudentController.php @@ -5,11 +5,13 @@ namespace App\Http\Controllers; use App\Models\School; use App\Models\Student; use App\Models\User; +use App\Rules\UniqueFullNameAtSchool; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use function abort; use function redirect; +// TODO validation rules to make sure a student name is unique at a school class StudentController extends Controller { /** @@ -37,7 +39,7 @@ class StudentController extends Controller if ($request->user()->cannot('create', Student::class)) abort(403); $request->validate([ 'first_name' => ['required'], - 'last_name' => ['required'], + 'last_name' => ['required', new UniqueFullNameAtSchool(request('first_name'),request('last_name'), Auth::user()->school_id)], 'grade' => ['required', 'integer'], ]); diff --git a/app/Rules/UniqueFullNameAtSchool.php b/app/Rules/UniqueFullNameAtSchool.php new file mode 100644 index 0000000..f67a8aa --- /dev/null +++ b/app/Rules/UniqueFullNameAtSchool.php @@ -0,0 +1,43 @@ +first_name = $firstName; + $this->last_name = $lastName; + $this->school_id = $schoolID; + } + + public function passes($attributies, $value) + { + return Student::where('first_name', $this->first_name) + ->where('last_name', $this->last_name) + ->where('school_id', $this->school_id) + ->exists(); + } + + public function message() + { + return "There is already a student with that name at the school you are trying to add them to"; + } + /** + * Run the validation rule. + * + * @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail + */ + public function validate(string $attribute, mixed $value, Closure $fail): void + { + // + } +}