Skip to content

Instantly share code, notes, and snippets.

@Aslam97
Last active October 11, 2021 13:54
Show Gist options
  • Save Aslam97/4c320dac0c50f3bbfd64164ad8fdd61a to your computer and use it in GitHub Desktop.
Save Aslam97/4c320dac0c50f3bbfd64164ad8fdd61a to your computer and use it in GitHub Desktop.
Laravel change user password

Laravel change user password

Create Custom Validation Rules

  • Create CheckPassword rules

php artisan make:rule CheckPassword

use Illuminate\Contracts\Validation\Rule;
use Hash;
use Auth;
...

public function passes($attribute, $value)
{
    return Hash::check($value, Auth::user()->password);
}

public function message()
{
    return trans('validation.check_password');
}
  • Create ComparePassword rules

php artisan make:rule ComparePassword

use Illuminate\Contracts\Validation\Rule;
...

public $current_password;

public function __construct($current_password)
{
    $this->current_password = $current_password;
}
    
public function passes($attribute, $value)
{
    return strcmp($this->current_password, $value) == 0 ? false : true;
}

public function message()
{
    return trans('validation.compare_password');
}

Create Form Requests

php artisan make:request UserChangePassword

use Illuminate\Foundation\Http\FormRequest;
use App\Rules\CheckPassword;
use App\Rules\ComparePassword;
...

public function authorize()
{
    return true;
}

public function rules()
{
    return [
        'current_password' => ['required', 'string', new CheckPassword],
        'new_password' => ['required', 'string', 'min:8', new ComparePassword($this->current_password)]
    ];
}

routes/web.php

Route::post('/password/change', 'Controller@changePassword');

Controller

use App\Http\Requests\UserChangePassword;
...

public function changePassword(UserChangePassword $request)
{
    auth()->user()->update(['password' => bcrypt($request->new_password)]);
    return response()->json(['message' => trans('validation.change_password')]);
}

Translations

  • lang/validation.php
'check_password' => 'Your current password does not match the password you provided.',
'compare_password' => 'The new password cannot be the same as your current password. Please choose a different password.',
'change_password' => 'Password change successfully.',
@dricislam
Copy link

Thank you so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment