# Laravel 的 验证旧密码的验证代码

- Link: https://www.ixiqin.com/2017/12/29/laravel-old-password-authentication-code/
- Published: 2017-12-29T15:34:17+08:00
- Author: 白宦成

更新密码这是一个非常常用的功能，我们需要为用户提供一个更改密码的方式。安全一些的
方式是通过验证旧密码，再更新密码，以免由于“记住我”功能导致的密码被盗改。
 一般来说，
Laravel 的更改密码都是通过 RestPassword Email 来实现的，但是我更倾向用户可以在后台
更改。所以，便在这里贴下相关的代码，借助下方的代码，可以实现验证用户密码，旧密码
验证通过后，再进行新的密码的更新。 在** App\Providers\AppServiceProvider** 中的 **
Boot** 方法中添加如下代码。

    ```php
    Validator::extend('password_hash_check', function($attribute, $value, $parameters, $validator) {
                return Hash::check($value , $parameters[0]) ;
            });
    ```

在对应的表单请求中，添加如下的调用。

    ```null
    use Auth;
    /**
         * Get the validation rules that apply to the request.
         *
         * @return array
         */
        public function rules()
        {
            $password = Auth::user()->password;
            return [
                'old_password' => "required|password_hash_check:" . $password,
                "password" => "required|min:6|max:25|confirmed",
            ];
        }
    ```

（上述代码采用的是表单请求的方式来进行验证的,使用方法参看：[Validation](https://laravel.com/docs/5.4/validation#creating-form-requests)）
