NewPasswordController.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 Inertia\Inertia;
  14. use Inertia\Response;
  15. class NewPasswordController extends Controller
  16. {
  17. /**
  18. * Show the password reset page.
  19. */
  20. public function create(Request $request): Response
  21. {
  22. return Inertia::render('auth/ResetPasswordPage', [
  23. 'email' => $request->email,
  24. 'token' => $request->route('token'),
  25. ]);
  26. }
  27. /**
  28. * Handle an incoming new password request.
  29. *
  30. * @throws \Illuminate\Validation\ValidationException
  31. */
  32. public function store(Request $request): RedirectResponse
  33. {
  34. $request->validate([
  35. 'token' => 'required',
  36. 'email' => 'required|email',
  37. 'password' => ['required', 'confirmed', Rules\Password::defaults()],
  38. ]);
  39. // Here we will attempt to reset the user's password. If it is successful we
  40. // will update the password on an actual user model and persist it to the
  41. // database. Otherwise we will parse the error and return the response.
  42. $status = Password::reset($request->only('email', 'password', 'password_confirmation', 'token'), function (User $user) use ($request) {
  43. $user
  44. ->forceFill([
  45. 'password' => Hash::make($request->password),
  46. 'remember_token' => Str::random(60),
  47. ])
  48. ->save();
  49. event(new PasswordReset($user));
  50. });
  51. // If the password was successfully reset, we will redirect the user back to
  52. // the application's home authenticated view. If there is an error we can
  53. // redirect them back to where they came from with their error message.
  54. if ($status == Password::PasswordReset) {
  55. return to_route('login')->with('status', __($status));
  56. }
  57. throw ValidationException::withMessages([
  58. 'email' => [__($status)],
  59. ]);
  60. }
  61. }