Ad

Laravel Empty Password Hashing

When I trying to update user data and let The Password Field empty it hashed again that means the password will change and you can't log in again so is there any way to fix this problem ??

Code

$this->validate($request, [
        'first_name'=> 'required|string',
        'last_name' =>  'required|string',
        'email'     =>  'required|email|unique:users,email,'.Auth::id(),
        'password'  =>  'sometimes|nullable|string|min:8,'.Auth::id(),
        'avatar'    =>  'image|mimes:jpg,jpeg,gif,png,svg|max:2048,'.Auth::id(),
        'gender'    =>  'required',
        'country_id'=>  'required',
    ]);

    $user = User::find(Auth::id());

    $user->first_name = $request->first_name;
    $user->last_name = $request->last_name;
    $user->email = $request->email;
    $user->gender = $request->gender;
    $user->country_id = $request->country_id;
    $user->password = bcrypt(request('password'));
    if($request->hasFile('avatar')){
        $avatar = $request->file('avatar');
        $filename = time() . '.' . $avatar->getClientOriginalExtension();
        Image::make($avatar)->resize(300, 300)->save( public_path('/images/avatars/' . $filename ) );
        $user->avatar = $filename;
    }

    $user->save();

    return redirect()->back();
Ad

Answer

You need to check if there is a passoword in the request object first.

if($request->password){
 $user->password = bcrypt(request('password'));
}

After editing it, it will be like this:

$this->validate($request, [
    'first_name'=> 'required|string',
    'last_name' =>  'required|string',
    'email'     =>  'required|email|unique:users,email,'.Auth::id(),
    'password'  =>  'sometimes|nullable|string|min:8,'.Auth::id(),
    'avatar'    =>  'image|mimes:jpg,jpeg,gif,png,svg|max:2048,'.Auth::id(),
    'gender'    =>  'required',
    'country_id'=>  'required',
]);

$user = User::find(Auth::id());

$user->first_name = $request->first_name;
$user->last_name = $request->last_name;
$user->email = $request->email;
$user->gender = $request->gender;
$user->country_id = $request->country_id;

if($request->password){
    $user->password = bcrypt(request('password'));
}

if($request->hasFile('avatar')){
    $avatar = $request->file('avatar');
    $filename = time() . '.' . $avatar->getClientOriginalExtension();
    Image::make($avatar)->resize(300, 300)->save( public_path('/images/avatars/' . $filename ) );
    $user->avatar = $filename;
}

$user->save();

return redirect()->back();
Ad
source: stackoverflow.com
Ad