Here’s a general guide on how to create a forgot password API in Laravel. This involves using Laravel’s built-in password reset functionality.
Steps to Create Forgot Password API in Laravel:
- Install a New Laravel Project: If you don’t have a Laravel project, you can create one using Composer:
composer create-project --prefer-dist laravel/laravel your-project-name
- Set Up Database: Configure your database connection in the
.env
file. - Run Migrations: Run the following command to create the necessary tables:
php artisan migrate
Now in Laravel 10 you get a preinstall sanctum package
Implement Password Reset Routes: Open routes/web.php
(for web routes) or routes/api.php
(for API routes) and include the following:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Models\User;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
// Forgot Password
Route::post('/forgot-password', function (Request $request) {
$request->validate(['email' => 'required|email']);
$status = Password::sendResetLink(
$request->only('email')
);
return $status === Password::RESET_LINK_SENT
? response()->json(['status' => __($status)])
: response()->json(['email' => __($status)]);
})->middleware('guest')->name('password.email');
Route::get('/reset-password/{token}', function (string $token) {
return response()->json(['token' => $token]);
// return view('auth.reset-password', ['token' => $token]);
})->middleware('guest')->name('password.reset');
Route::post('/reset-password', function (Request $request) {
$request->validate([
'token' => 'required',
'email' => 'required|email',
'password' => 'required|min:8|confirmed',
]);
$status = Password::reset(
$request->only('email', 'password', 'password_confirmation', 'token'),
function (User $user, string $password) {
$user->forceFill([
'password' => Hash::make($password)
])->setRememberToken(Str::random(60));
$user->save();
event(new PasswordReset($user));
}
);
return $status === Password::PASSWORD_RESET
? response()->json(['status' => $status])
: response()->json(['email' => [__($status)]]);
// return $status === Password::PASSWORD_RESET
// ? redirect()->route('login')->with('status', __($status))
// : back()->withErrors(['email' => [__($status)]]);
})->middleware('guest')->name('password.update');
Reset Link Customization:
You may customize the password reset link URL using the createUrlUsing
method provided by the ResetPassword
notification class. This method accepts a closure which receives the user instance that is receiving the notification as well as the password reset link token. Typically, you should call this method from your App\Providers\AuthServiceProvider
service provider’s boot
method:
<?php
namespace App\Providers;
use App\Models\User;
use Illuminate\Auth\Notifications\ResetPassword;
// use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The model to policy mappings for the application.
*
* @var array<class-string, class-string>
*/
protected $policies = [
//
];
/**
* Register any authentication / authorization services.
*/
public function boot(): void
{
ResetPassword::createUrlUsing(function (User $user, string $token) {
$frontendUrl = env('FRONTEND_URL'); // Replace 'FRONTEND_URL' with your actual key
return $frontendUrl.'?url=' . url("/api/reset-password/{$token}?email={$user->email}");
});
}
}
and update your .env
file with
FRONTEND_URL="https://yourfrontend.vercel.app/reset-password"