change password user laravel 5.3

前端 未结 5 1421
终归单人心
终归单人心 2021-01-30 11:00

I want to create form with 3 field (old_password, new_password, confirm_password) with laravel 5.

View

old password : {!! Form::password(

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-30 11:52

    This is how I do this with Laravel 5.8:

    View

    Confirm password must be something like this:

    {!! Form::password('password_confirmation', ['class' => 'form-control'']) !!}
    

    Because Laravel provides out the box a field confirmed rule.

    Create a form request and put this inside the rules part:

    use App\Rules\IsCurrentPassword;
    
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'old_password' => ['required', new IsCurrentPassword],
            'password' => 'required|string|min:6|confirmed',
        ];
    }
    

    Let's use artisan to generate a rule that verifies if old_password is the real current password:

    php artisan make:rule IsCurrentPassword
    

    And put this inside the passes method of rule generated:

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $current_password = auth()->user()->password;
        return Hash::check($value, $current_password);
    }
    

    Do not forget to import Hash:

    use Illuminate\Support\Facades\Hash;
    

    Controller

    All you need to do in your controller is this:

    auth()->user()->update([
        'password' => Hash::make($request->password)
    ]);
    

    And tada :) Hope I help.

提交回复
热议问题