更改密码用户laravel 5.3

时间:2016-09-20 05:09:20

标签: php forms laravel laravel-5

我想用laravel 5创建包含3个字段(old_password,new_password,confirm_password)的表单。

查看

旧密码: {!! 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中的密码,但它对我没有帮助。

如何在控制器中为更改密码用户编写代码? 在此先感谢。

5 个答案:

答案 0 :(得分:42)

这是更改密码表格

<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|same:password',
    '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('/');
  }    
}

答案 1 :(得分:4)

我在这里说明了另一种更改用户密码的方法 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 :(得分:1)

Laravel 6 Check Old Password and Updating a New Password

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

        }
    }

答案 3 :(得分:0)

这就是我使用Laravel 5.8的方法:

查看

确认密码必须是这样的:

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

因为Laravel在框中提供了confirmed rule字段。

创建一个表单请求,并将其放入规则部分:

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

让我们使用技术人员来生成一条规则来验证old_password是否为当前的真实密码:

php artisan make:rule IsCurrentPassword

并将其放入生成的规则的passs方法中:

/**
 * 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)
]);

还有tada :)希望我能帮忙。

答案 4 :(得分:-1)

<强> changePassword.blade.php

AcademicInformation

控制器发布功能

Student