Created
July 14, 2020 14:37
-
-
Save shibbirweb/70e2e0f410ee3e7f596cf7b3c78a2661 to your computer and use it in GitHub Desktop.
Add additional Logical validation in Laravel FormRequest
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\Http\Requests; | |
| use Illuminate\Contracts\Validation\Validator; | |
| use Illuminate\Foundation\Http\FormRequest; | |
| use Illuminate\Support\Facades\Hash; | |
| class ProfileUpdatePasswordRequest extends FormRequest | |
| { | |
| /** | |
| * Determine if the user is authorized to make this request. | |
| * | |
| * @return bool | |
| */ | |
| public function authorize() | |
| { | |
| // check user is logged or not | |
| return auth()->check(); | |
| } | |
| /** | |
| * Get the validation rules that apply to the request. | |
| * | |
| * @return array | |
| */ | |
| public function rules() | |
| { | |
| return [ | |
| 'current_password' => 'bail|required|string|max:255', | |
| 'new_password' => 'bail|required|string|max:255|confirmed|min:8', | |
| ]; | |
| } | |
| /** | |
| * Validator instance | |
| * @param Validator $validator | |
| */ | |
| public function withValidator(Validator $validator): void | |
| { | |
| $validator->after([$this, "afterValidation"]); | |
| } | |
| /** | |
| * After Rule validation | |
| * @param Validator $validator | |
| */ | |
| public function afterValidation(Validator $validator) | |
| { | |
| // validate current user password | |
| $this->didMatchCurrentPassword($validator); | |
| } | |
| /** | |
| * Check Current user password match or not | |
| * @param Validator $validator | |
| */ | |
| private function didMatchCurrentPassword(Validator $validator) | |
| { | |
| // typed current password in form | |
| $typed_current_password = $this->input('current_password'); | |
| // if current password not match with auth password | |
| if (! Hash::check($typed_current_password, auth()->user()->getAuthPassword())){ | |
| $validator->errors()->add('current_password', 'Current password did not match'); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment