更改 Laravel 5.3 用户密码

34

我想用Laravel 5创建一个包含3个字段(旧密码、新密码、确认密码)的表单。

视图

旧密码: {!! Form::password('old_password',['class' => 'form-control']) !!}

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

确认新密码: {!! Form::password('verify_password',['class' => 'form-control']) !!}

当用户注册时的控制器

public function postRegister(Request $request)
{
    $rules = [
        'email'             =>  'required|email|unique:users',
        'confirm_email'     =>  'required|same:email',
        'password'          =>  'required|min:8|regex:/^(?=\S*[a-z])(?=\S*[!@#$&*])(?=\S*[A-Z])(?=\S*[\d])\S*$/',
        'verify_password'   =>  'required|same:password',
    ];

    $messages = [
        'email.required'            => 'email tidak boleh kosong',
        'password.required'         => 'password tidak boleh kosong',
        'password.min'              => 'Password harus minimal 8 karakter',
        'password.regex'            => 'Format password harus terdiri dari kombinasi huruf besar, angka dan karakter spesial (contoh:!@#$%^&*?><).',
        'verify_password.required'  => 'Verify Password tidak boleh kosong',
        'email.email'               => 'Format Email tidak valid',
        'email.unique'              => 'Email yang anda masukkan telah digunakan',
        'verify_password.same'      => 'Password tidak sama!',
    ];

    $this->validate($request,$rules,$messages);


    $newUser = $this->user->create([
        'email'         =>  $request->email,
        'password'      =>  \Hash::make($request->password),
    ]);
    $this->activationService->sendActivationMail($newUser);

    return redirect('/account/login')->with('success', 'Check your email');
}

我是laravel的新手,我在stackoverflow上读了一些类似的更改密码问题,但它们并没有帮助到我。

我应该如何在我的控制器中编写代码来更改用户的密码?谢谢提前。


你可以使用内置的密码控制器。 - Sanzeeb Aryal
1
如果你想手动操作,必须要研究 vendor\laravel\framework\src\Illuminate\Foundation\Auth\ResetsPasswords\PasswordController.php 页面。 - Manish
4
请查看此链接 https://www.5balloons.info/setting-up-change-password-with-laravel-authentication/ - jpussacq
6个回答

60

这是修改密码表单

<form id="form-change-password" role="form" method="POST" action="{{ url('/user/credentials') }}" novalidate class="form-horizontal">
  <div class="col-md-9">             
    <label for="current-password" class="col-sm-4 control-label">Current Password</label>
    <div class="col-sm-8">
      <div class="form-group">
        <input type="hidden" name="_token" value="{{ csrf_token() }}"> 
        <input type="password" class="form-control" id="current-password" name="current-password" placeholder="Password">
      </div>
    </div>
    <label for="password" class="col-sm-4 control-label">New Password</label>
    <div class="col-sm-8">
      <div class="form-group">
        <input type="password" class="form-control" id="password" name="password" placeholder="Password">
      </div>
    </div>
    <label for="password_confirmation" class="col-sm-4 control-label">Re-enter Password</label>
    <div class="col-sm-8">
      <div class="form-group">
        <input type="password" class="form-control" id="password_confirmation" name="password_confirmation" placeholder="Re-enter Password">
      </div>
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-5 col-sm-6">
      <button type="submit" class="btn btn-danger">Submit</button>
    </div>
  </div>
</form>

创建规则

public function admin_credential_rules(array $data)
{
  $messages = [
    'current-password.required' => 'Please enter current password',
    'password.required' => 'Please enter password',
  ];
  
  $validator = Validator::make($data, [
    'current-password' => 'required',
    'password' => 'required',
    'password_confirmation' => 'required|same:password',     
  ], $messages);

  return $validator;
}  

用户控制器方法修改密码

使用 Validator;

public function postCredentials(Request $request)
{
  if(Auth::Check())
  {
    $request_data = $request->All();
    $validator = $this->admin_credential_rules($request_data);
    if($validator->fails())
    {
      return response()->json(array('error' => $validator->getMessageBag()->toArray()), 400);
    }
    else
    {  
      $current_password = Auth::User()->password;           
      if(Hash::check($request_data['current-password'], $current_password))
      {           
        $user_id = Auth::User()->id;                       
        $obj_user = User::find($user_id);
        $obj_user->password = Hash::make($request_data['password']);
        $obj_user->save(); 
        return "ok";
      }
      else
      {           
        $error = array('current-password' => 'Please enter correct current password');
        return response()->json(array('error' => $error), 400);   
      }
    }        
  }
  else
  {
    return redirect()->to('/');
  }    
}

4
为什么要检查当前密码是否至少有8个字符?也许用户的密码少于8个字符,他需要把它改为大于等于8个字符。 - Robin Dirksen
添加一行代码 'use Validator;',你需要使用验证器。 - Komal
2
然后返回如下::= return redirect()->back()->withErrors($validator)->withInput(); - Komal
2
做得好,Komal。我简直不敢相信这个功能在Laravel中没有默认提供!毕竟,已登录的用户可能需要像忘记密码的用户一样经常更改密码! :) - DigiOz Multimedia
需要在“密码”和“确认密码”规则的两个规则中都使用“same:password”吗? - badjuice
显示剩余12条评论

12

我在这里解释另一种改变用户密码的方法changepassword.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Change password</div>

                <div class="panel-body">
                    @if (session('error'))
                        <div class="alert alert-danger">
                            {{ session('error') }}
                        </div>
                    @endif
                        @if (session('success'))
                            <div class="alert alert-success">
                                {{ session('success') }}
                            </div>
                        @endif
                    <form class="form-horizontal" method="POST" action="{{ route('changePassword') }}">
                        {{ csrf_field() }}

                        <div class="form-group{{ $errors->has('current-password') ? ' has-error' : '' }}">
                            <label for="new-password" class="col-md-4 control-label">Current Password</label>

                            <div class="col-md-6">
                                <input id="current-password" type="password" class="form-control" name="current-password" required>

                                @if ($errors->has('current-password'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('current-password') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('new-password') ? ' has-error' : '' }}">
                            <label for="new-password" class="col-md-4 control-label">New Password</label>

                            <div class="col-md-6">
                                <input id="new-password" type="password" class="form-control" name="new-password" required>

                                @if ($errors->has('new-password'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('new-password') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="new-password-confirm" class="col-md-4 control-label">Confirm New Password</label>

                            <div class="col-md-6">
                                <input id="new-password-confirm" type="password" class="form-control" name="new-password_confirmation" required>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Change Password
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

这是在 web.php 中的路由

Route::post('/changePassword','HomeController@changePassword')->name('changePassword');

控制器方法

public function changePassword(Request $request){

        if (!(Hash::check($request->get('current-password'), Auth::user()->password))) {
            // The passwords matches
            return redirect()->back()->with("error","Your current password does not matches with the password you provided. Please try again.");
        }

        if(strcmp($request->get('current-password'), $request->get('new-password')) == 0){
            //Current password and new password are same
            return redirect()->back()->with("error","New Password cannot be same as your current password. Please choose a different password.");
        }

        $validatedData = $request->validate([
            'current-password' => 'required',
            'new-password' => 'required|string|min:6|confirmed',
        ]);

        //Change Password
        $user = Auth::user();
        $user->password = bcrypt($request->get('new-password'));
        $user->save();

        return redirect()->back()->with("success","Password changed successfully !");

    }

我已经跟随这个链接: - https://www.5balloons.info/setting-up-change-password-with-laravel-authentication/


2
谢谢,这些是教程中缺失的代码片段。所有内容一起为我提供了一个不错的Laravel 5.7解决方案。 - Blue Box
1
这个对我很有效。谢谢! - 尤川豪
2
谢谢兄弟,它起作用了!别忘了在你的控制器中导入这些类: use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Auth; - Freddy Daniel

2

Laravel 6 检查旧密码并更新新密码

public function updatePassword(Request $request)
    {
        $this->validate($request, [
            'old_password'     => 'required',
            'new_password'     => 'required|min:6',
            'confirm_password' => 'required|same:new_password',
        ]);

        $data = $request->all();

        if(!\Hash::check($data['old_password'], auth()->user()->password)){

             return back()->with('error','You have entered wrong password');

        }else{

           here you will write password update code

        }
    }

2
这是我在Laravel 5.8中的做法: 视图 确认密码必须像这样:
"Original Answer" 翻译成 "最初的回答"
{!! Form::password('password_confirmation', ['class' => 'form-control'']) !!}

因为Laravel提供了一个名为“confirmed”的规则,可以直接使用。在表单请求中添加以下规则即可:

confirmed

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',
    ];
}

让我们使用Artisan生成一个规则来验证old_password是否是真正的当前密码: "使用Artisan生成一个规则来验证old_password是否是真正的当前密码:"
php artisan make:rule IsCurrentPassword

将此放入生成规则的passes方法中:
/**
 * 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);
}

不要忘记导入Hash:最初的回答
use Illuminate\Support\Facades\Hash;

控制器

在你的控制器中,你只需要这样做:

所有你需要做的就是:

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

最初的回答。完成啦 :) 希望我能帮到你。

0
您也可以使用此代码重置密码。
public function passwordReset(Request $request)
{
    $input = $request->all();
    $validated = $request->validate(
        [
            'current_password' => 'required',
            'password' => 'required|confirmed'
        ]
    );
    //Change Password
    $username = Auth::user();
    $name = $username->username;
    $currentpassword = $input['current_password'];
    $password = $input['password'];
    $result = DB::table('user_security')
        ->where('username', $name)
        ->get();

    $cpassword =  $result[0]->password;
    if (Hash::check($currentpassword, $cpassword)) {
        $insert = DB::table('user_security')
            ->where('username', $name)
            ->update([
                'password' =>  Hash::make($password)
            ]);
        return redirect('viewprofile');
    } else {
        return redirect('changepassword');
    }
}

0

changePassword.blade.php

@extends('layouts.app')

@section('content')
    <!-- header logo: style can be found in header.less -->
    <header class="header">
        <div class="container">
            <div class="row">
                <div class="col-lg-6">
                <a href="index.php" class="logo">
                    <!-- Add the class icon to your logo image or logo icon to add the margining -->
                    <img src="img/airbus-logo.png" />
                </a></div>
                <!-- Header Navbar: style can be found in header.less -->
                <div class="col-lg-6">
                    @include('partials._userModal')
                    @include('partials._menu')
                </div>
            </div>
        </div>
    </header>
    <div class="wrapper">
        <div class="container">
            <!-- Right side column. Contains the navbar and content of the page -->
            <aside class="content files-list clearfix">
                <h2>
                @if(Auth::check())
                Welcome {{ Auth::user()->fullName }}
                @endif
                </h2>
                    <div class="col-xs-5">
                        <h4>Change password</h4><br />
                        @if($errors->any())
                            @foreach($errors->all() as $error)
                                <p style='padding:15px;' class='bg-danger'>{{ $error }}</p>
                            @endforeach
                        @endif
                        @if(Request::get('errorMessage') !== null)
                            <p style='padding:15px;' class='bg-danger'>{{ Request::get('errorMessage') }}</p>
                        @endif
                        <form method="post">
                            {{ csrf_field() }}
                           <div class="placeholder">Current Password</div>
                            <input style="max-width:200px;" placeholder='Current password' name="oldpass" id="oldpass"  class="form-control" type="password"><br>
                            <div class="placeholder">New password</div>
                            <input style="max-width:200px;" placeholder='New password' name="password" id="password"  class="form-control" type="password"><br>
                            <div class="placeholder">Confirm password</div>
                            <input id="password_confirmation" style="max-width:200px;" placeholder='Confirm password' name="password_confirmation"  class="form-control" type="password">
                            <hr>
                            <input type="submit" class="btn btn-primary" value="Save">
                        </form>    
                    </div>
            </aside>
            <!-- /.right-side -->
        </div>
        <div style="  height: 155px;"></div>
        <div id="footer">
            <div class="container"> © Airbus Group 2015 </div>
        </div>
    </div>
    <!-- ./wrapper -->
    <!-- <script src="js/hub/demo.js" type="text/javascript"></script> -->
<script type="text/javascript">
    $(document).ready(function(){
        var bHeight = $("body").height();
        var wHeight = $( window ).height();
        if(bHeight < wHeight){
            $("#footer").addClass("absolute");
        }else{
            $("#footer").removeClass("absolute");
        }
        if (!$.support.htmlSerialize && !$.support.opacity){
            $(".placeholder").show();
        }
    });
</script>
@endsection

控制器发布函数

public function postChangePassword(Request $request)
    {
        $validatedData = $request->validate([
            'oldpass' => 'required|min:6',
            'password' => 'required|string|min:6',
            'password_confirmation' => 'required|same:password',
        ],[
            'oldpass.required' => 'Old password is required',
            'oldpass.min' => 'Old password needs to have at least 6 characters',
            'password.required' => 'Password is required',
            'password.min' => 'Password needs to have at least 6 characters',
            'password_confirmation.required' => 'Passwords do not match'
        ]);

        $current_password = \Auth::User()->password;           
        if(\Hash::check($request->input('oldpass'), $current_password))
        {          
          $user_id = \Auth::User()->id;                       
          $obj_user = User::find($user_id);
          $obj_user->password = \Hash::make($request->input('password'));
          $obj_user->save(); 
          return view('auth.passwords.changeConfirmation');
        }
        else
        {           
          $data['errorMessage'] = 'Please enter correct current password';
          return redirect()->route('user.getChangePassword', $data);
        }  
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接