Pada kasus kali ini saya menggunakan Laravel 8 (buat API) frontend Vue Js:
Pertama siapkan routingnya pada folder routes - api.php
Route::post('forgot-password', [UserController::class, 'forgotPassword']);
Route::post('reset-password', [UserController::class, 'resetPassword']);
Tambahkan di UserController.php atau anda bisa nambah controller baru.
public function forgotPassword(Request $request)
{
$request->validate(['email' => 'required|email']);
$status = Password::sendResetLink(
$request->only('email')
);
if($status == Password::RESET_LINK_SENT){
return [
'status' => __($status)
];
}
throw ValidationException::withMessages([
'email' => [trans($status)],
]);
}
public function resetPassword(Request $request)
{
$request->validate([
'token' => 'required',
'email' => 'required|email',
'password' => ['required', 'confirmed', RulesPassword::defaults()],
]);
$status = Password::reset(
$request->only('email', 'password', 'password_confirmation', 'token'),
function ($user) use ($request) {
$user->forceFill([
'password'=> Hash::make($request->password),
'remember_token' => Str::random(60),
])->save();
event(new PasswordReset($user));
}
);
if($status == Password::PASSWORD_RESET){
return response([
'message' => 'Password reset successfully'
]);
}
return response([
'message' => __($status)
], 500);
}
Tambahkan di model User.php
public function sendPasswordResetNotification($token)
{
$url = 'http://localhost:8000/reset-password?token=' . $token;
$this->notify(new ResetPasswordNotification($url));
}
Jalankan notification reset password melalui terminal
php artisan make:notification ResetPasswordNotification
Lalu buka file ResetPasswordNotification.php
Tambahkan url
public $url;
public function __construct(string $url)
{
$this->url = $url;
}
public function toMail($notifiable)
{
return (new MailMessage)
->line('Forgot Password?')
->action('Click to reset', $this->url)
->line('Thank you for using our application!');
}
Langkah selanjutnya tinggal testing apakah berjalan dengan lancar
http://localhost:8000/api/forgot-password{
"status": "We have emailed your password reset link!"
} artinya sudah dikirim ke email
http://localhost:8000/api/reset-password
Jangan lupa samakan ubah config .env
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=xxxx
MAIL_PASSWORD=xxxx
MAIL_ENCRYPTION=tls
Jika menggunakan gmail setting dulu di bagian keamanan - akses aplikasi yang kurang aman di uncheclist.
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=72ce0f2cdeb928
MAIL_PASSWORD=80c25747b32926
MAIL_ENCRYPTION=tls
Komentar