NewPasswordController.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace App\Http\Controllers\Auth;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\User;
  5. use Illuminate\Auth\Events\PasswordReset;
  6. use Illuminate\Http\RedirectResponse;
  7. use Illuminate\Http\Request;
  8. use Illuminate\Support\Facades\Hash;
  9. use Illuminate\Support\Facades\Password;
  10. use Illuminate\Support\Str;
  11. use Illuminate\Validation\Rules;
  12. use Illuminate\Validation\ValidationException;
  13. use Illuminate\View\View;
  14. class NewPasswordController extends Controller
  15. {
  16. /**
  17. * Display the password reset view.
  18. */
  19. public function create(Request $request): View
  20. {
  21. return view('auth.reset-password', ['request' => $request]);
  22. }
  23. /**
  24. * Handle an incoming new password request.
  25. *
  26. * @throws ValidationException
  27. */
  28. public function store(Request $request): RedirectResponse
  29. {
  30. $request->validate([
  31. 'token' => ['required'],
  32. 'email' => ['required', 'email'],
  33. 'password' => ['required', 'confirmed', Rules\Password::defaults()],
  34. ]);
  35. // Here we will attempt to reset the user's password. If it is successful we
  36. // will update the password on an actual user model and persist it to the
  37. // database. Otherwise we will parse the error and return the response.
  38. $status = Password::reset(
  39. $request->only('email', 'password', 'password_confirmation', 'token'),
  40. function (User $user) use ($request) {
  41. $user->forceFill([
  42. 'password' => Hash::make($request->password),
  43. 'remember_token' => Str::random(60),
  44. ])->save();
  45. event(new PasswordReset($user));
  46. }
  47. );
  48. // If the password was successfully reset, we will redirect the user back to
  49. // the application's home authenticated view. If there is an error we can
  50. // redirect them back to where they came from with their error message.
  51. return $status == Password::PASSWORD_RESET
  52. ? redirect()->route('login')->with('status', __($status))
  53. : back()->withInput($request->only('email'))
  54. ->withErrors(['email' => __($status)]);
  55. }
  56. }