Created
October 19, 2020 12:20
-
-
Save shibbirweb/3636b1a63db10b7716a7ad40312a0750 to your computer and use it in GitHub Desktop.
Custom Laravel Validation Rule
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Rules; | |
| use App\Models\Subject; | |
| use Illuminate\Contracts\Validation\Rule; | |
| use Illuminate\Http\Request; | |
| use Illuminate\Support\Str; | |
| class ExistsTopicInSubjectRule implements Rule | |
| { | |
| private $request, $subject_key; | |
| /** | |
| * Create a new rule instance. | |
| * | |
| * @param Request $request Request instance | |
| * @param string $subjectKey Form subject key | |
| */ | |
| public function __construct(Request $request, string $subjectKey) | |
| { | |
| $this->request = $request; | |
| $this->subject_key = $subjectKey; | |
| } | |
| /** | |
| * Determine if the validation rule passes. | |
| * | |
| * @param string $attribute | |
| * @param mixed $value | |
| * @return bool | |
| */ | |
| public function passes($attribute, $value) | |
| { | |
| $subject = $this->findSubject($this->request, $attribute, $this->subject_key); | |
| if (!$subject) { | |
| return false; | |
| } | |
| $topic = $subject->topics() | |
| ->whereId($value) | |
| ->first(); | |
| return $topic ? true : false; | |
| } | |
| /** | |
| * Get the validation error message. | |
| * | |
| * @return string | |
| */ | |
| public function message() | |
| { | |
| return 'The selected :attribute is invalid.'; | |
| } | |
| /** | |
| * Find Subject | |
| * | |
| * @param Request $request Request instance | |
| * @param string $attribute Current validation attribute | |
| * @param string $subject_key Subject key in request instance | |
| * @return Subject|null Subject model or null | |
| */ | |
| private function findSubject(Request $request, string $attribute, string $subject_key): ?Subject | |
| { | |
| $subject_key = Str::of($attribute)->beforeLast('.')->append('.', $subject_key); | |
| $subject_id = $request->$subject_key; | |
| return Subject::find($subject_id); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment