Laravel实现修改密码操作
在LoginController.php中加入reset代码:
引入验证库:
use Illuminate\Support\Facades\Validator;
控制器代码如下:
数据库更新使用$user->update();
,去除updated_at需要在Model中加入public $timestamps=false;
// 修改密码
public function reset(){
if ($input=Input::all()) {
$rules = [
'origin_pass'=>'required',
'new_pass'=>'required|between:6,20|confirmed',
];
$msg = [
'required'=>'密码不能为空!',
'new_pass.between'=>'密码必须在6~20位之间!',
'new_pass.confirmed'=>'新密码与确认密码不一致!',
];
$validator = Validator::make($input,$rules,$msg);
if ($validator->passes()) {
$user = User::where('username',session()->get('user')->username)->first();
if (!$user || $user&&Crypt::decrypt($user->password)!=$input['origin_pass']) {
return back()->withErrors('原密码错误!');
}
$user->password = Crypt::encrypt($input['new_pass']);
$user->update(); // 更新密码
session(['user'=>null]);
return redirect('admin/login');
}else{
return back()->withErrors($validator);
}
} else {
return view('admin/reset');
}
}
前端页面显示:
<div class="card card-small mb-4">
<ul class="list-group list-group-flush">
<li class="list-group-item p-3">
@if (count($errors)>0)
{{ $errors->first() }}
@else
<strong class="text-muted d-block mb-2">Forms</strong>
@endif
<form action="" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="origin_pass">原密码</label>
<input type="password" class="form-control" name="origin_pass" id="origin_pass" placeholder="">
</div>
<div class="form-group">
<label for="new_pass">新密码</label>
<input type="password" class="form-control" name="new_pass" id="new_pass" placeholder="">
</div>
<div class="form-group">
<label for="repeat_pass">确认密码</label>
<input type="password" class="form-control" name="new_pass_confirmation" id="repeat_pass" placeholder="">
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block">提交</button>
<button type="" class="btn btn-default btn-lg btn-block">返回</button>
</form>
</li>
</ul>
</div>