Reputation: 13569
I'm using the authentication included with laravel 5.2:
https://laravel.com/docs/5.2/authentication#included-routing
I want to implement a 'change password' functionality for authenticated users and I have two options:
I can use the included '/password/reset' route, not optimal but ok. But it only works when the user is not logged in. Can I make it work for authenticated users as well?
I can create an 'enter new password' form in a view and a updatePassword
method in UsersController
. But I need to check if the submitted password is not empty, that means the user wants to change it, then apply validation rules, then encrypt it and update it. Is it the right way of doing it? Any examples will be appreciated.
Upvotes: 1
Views: 5145
Reputation: 9199
I have implemented change password in my user file as below
public function postReset(Request $request)
{
$this->validate($request, [
'password' => 'required|confirmed','email' => 'required|email',
]);
$user = User::findOrFail($id);
$input = $request->input();
//Change Password if password value is set
if ($input['password'] != "") {
//dd(bcrypt($input['password']));
$input['password'] = bcrypt($input['password']);
}
$user->fill($input)->save();
}
Upvotes: 1
Reputation: 11257
You can set set attribute in model like
public function setPasswordAttribute($value)
{
$this->attributes['password'] = bcrypt($value);
}
In edit method:
if (empty($request->password)) {
$data = $request->except('password');
} else {
$data = $request->all();
}
$user = $this->userRepository->update($data, $id);
Upvotes: 1
Reputation: 25211
I think #2 is the way to go, it's just another field in the user settings form. In my app it looks like this:
$user->update($request->except('password'));
if($request->get('password') != ""){
$user->password = Hash::make($request->get('password'));
}
$user->save();
I do a special check to ensure I don't update the password from a blank field. Add validation to taste.
Upvotes: 1