auditionadmin/app/Rules/UniqueFullNameAtSchool.php

50 lines
1.2 KiB
PHP

<?php
namespace App\Rules;
use App\Models\Student;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Translation\PotentiallyTranslatedString;
class UniqueFullNameAtSchool implements ValidationRule
{
protected string $first_name;
protected string $last_name;
protected int $school_id;
public function __construct($firstName, $lastName, $schoolID)
{
$this->first_name = $firstName;
$this->last_name = $lastName;
$this->school_id = $schoolID;
}
public function studentExists(): bool
{
return Student::where('first_name', $this->first_name)
->where('last_name', $this->last_name)
->where('school_id', $this->school_id)
->exists();
}
public function message(): string
{
return 'There is already a student with that name at that school.';
}
/**
* Run the validation rule.
*
* @param Closure(string): PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if ($this->studentExists()) {
$fail($this->message());
}
}
}