简体   繁体   中英

how to update existing user table values with password confirmtion in laravel

I am working with Laravel 5.6 and going to update My user table values ( name , email , password ) as the system admin.

blade file

<form action="{{route('users.update',$user->id)}}" method="POST">
    {{method_field('PUT')}}
    {{csrf_field()}}

    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control" id="name" name="name" value="{{$user->name}}" >
    </div>
    <div class="form-group">
        <label for="email">Email</label>
        <input type="text" class="form-control" id="email" name="email" value="{{$user->email}}">
    </div>

    <div class="form-group">
        <label for="password">Password</label>
        <input type="password" class="form-control" id="password" name="password">
    </div>

    <div class="form-group">
        <label for="password_confirmation">Confirm Password</label>
        <input type="password" class="form-control" id="password_confirmation" name="password">
    </div>

    <button type="submit" class="btn btn-primary">Edit User</button>
</form>

and My controller,

public function update(Request $request, $id)
{
  $user = User::findOrFail($id);
  $user->name = $request->name;
  $user->uservalue = $request->uservalue;
  $user->email = $request->email;
  $user->password = bcrypt($request->input('password'));
  $user->save();

  return view('users.show')->withUser($user);
}

Problem

my password confirmation is not working

That means I can enter password without confirmation and or wrong confirmation password. How can I fix this problem?

You have to add a password confirm validation. For that to work, your second password field has to be called password_confirmation (or foo and foo_confirmation)

public function update(Request $request, $id)
{
  $user = User::findOrFail($id);
  $request->validate([
    'password' => 'sometimes|min:6|confirmed'
  ]);
  $user->name = $request->name;
  $user->uservalue = $request->uservalue;
  $user->email = $request->email;
  $user->password = bcrypt($request->input('password'));
  $user->save();

  return view('users.show')->withUser($user);
}

You can add more validation fields as explained here . If the validation fails, the browser will bring the user back to the update page. The errors are in the laravel errorbag available in your views as $errors .

sometimes means that the following rules are needed if there is an input. As you want to update user information, your visitors can leave the password field empty if they don't want to update the password. Unset the password field (if empty) before updating the user input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM