Laravel Reset Password Securely [100% Working]


Written by - Steve Alila
Reviewed by - Deepak Prasad

Welcome to this comprehensive guide on implementing Laravel reset password functionality and sending reset password link emails in Laravel applications. One of the essential features of any web application is the ability for users to securely reset their passwords, ensuring a smooth user experience and maintaining the security of their accounts.

In this article, we will explore how to build a robust Laravel reset password system, providing users with the ability to send reset password link emails using Laravel's built-in features. Laravel provides a straightforward way to implement password reset functionality using the Laravel Breeze package. Laravel Breeze is a lightweight authentication system with pre-built views and controllers for login, registration, and password reset functionality. We will walk you through the process of setting up the necessary components, configuring the email functionality, and customizing the user interface to create a seamless experience for your users.

By following this guide, you will not only learn how to implement the Laravel reset password feature, but also understand how to send reset password link emails in Laravel, making it easier for your users to recover their accounts in case they forget their passwords. So, let's dive in and learn how to create a user-friendly and secure password reset system for your Laravel applications!

 

Generate the authentication views and controllers

Run these commands to quickly and easily set up Laravel Breeze in your Laravel application and have a fully functional authentication system with login, registration, and password reset functionality.

Install Laravel Breeze as a development dependency in your Laravel application.

composer require laravel/breeze --dev

Generate the authentication scaffolding in your Laravel application. This includes the views and controllers required for login, registration, and password reset functionality. Running this command also adds the necessary routes to your routes/web.php file.

php artisan breeze:install

Install JavaScript dependencies required by Laravel Breeze. This includes packages like Laravel Mix, which is used to compile and minify the CSS and JavaScript assets.

npm install

This command compiles the CSS and JavaScript assets required by Laravel Breeze. It generates the public/css/app.css and public/js/app.js files that are included in the authentication views.

npm run dev

Runs the database migration required by Laravel Breeze. It creates the necessary database tables for authentication, including the users table and the password_resets table used for password reset functionality.

php artisan migrate

 

Configure email

Open the .env file and configure the email address according to the server. For example, you can set your Gmail credentials as follows.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=<your-gmail-username@gmail.com>
MAIL_PASSWORD=<your-gmail-password>
MAIL_ENCRYPTION=tls

My host and port differ from yours because I am using mail trap for the email testing feature.

MAIL_MAILER=smtp
MAIL_HOST=sandbox.smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=<mailtrap_email_id>
MAIL_PASSWORD=<mailtrap_password_id>
MAIL_ENCRYPTION=tls

The MAIL_USERNAME value in the Laravel .env file should be the email address from which you want to send emails. The MAIL_PASSWORD value should be the password for the email address you provided as the MAIL_USERNAME. This is required to authenticate and authorize the application to send emails on behalf of the email account.

 

Add the CanResetPassword trait to the User model

Open the app/Models/User.php file. Import the CanResetPassword contract then let the User class implement it.

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\CanResetPassword;

class User extends Authenticatable implements CanResetPassword
{
    use HasApiTokens, HasFactory, Notifiable;
 ...
}

The use Illuminate\Contracts\Auth\CanResetPassword; line imports the CanResetPassword contract to the current file before we implement it.

 

Create password_resets table

php artisan make:migration create_password_resets_table --create=password_resets

Here is a breakdown of the command and its parameters:

  • php artisan is a CLI command that runs Artisan, a command-line interface included with Laravel.
  • make:migration is a Laravel Artisan command that creates a new database migration file.
  • create_password_resets_table is the name of the migration file that will be created. This migration file is used to create a table for storing password reset tokens in the database.
  • --create=password_resets is a parameter that tells the make:migration command to create a new table named password_resets in the database.

 

Create Auth Routes

Password Reset Link Request Form

First, send a view with an email field for the user to reset their password

Route::get('/forgot-password', function () {
    return view('auth.forgot-password');
})->middleware('guest')->name('password.request');

Next, handle form submissions from requests coming from the forgot-password view. Laravel Breeze implements the route in routes/auth.php and controller in app/Http/Controllers/Auth/PasswordResetLinkController.php files, respectively. The route validates the user's email address before sending a reset password to the user.

use Illuminate\Http\Request;
use Illuminate\Support\Facades\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
                ? back()->with(['status' => __($status)])
                : back()->withErrors(['email' => __($status)]);
})->middleware('guest')->name('password.email');

We validate the email address using the $request object's validate method.

Laravel Reset Password Securely [100% Working]

 

Using the Password facade (password broker), we send a password reset link to the user. The facade retrieves a user by the given email field before sending them a reset password link with the help of Laravel's notification system .

Laravel Reset Password Securely [100% Working]

 

Password reset form

The user clicks on the reset password link emailed to them. The link takes them to your password reset form. The route receives a token parameter for subsequent password reset requests.

Route::get('/reset-password/{token}', function (string $token) {
    return view('auth.reset-password', ['token' => $token]);
})->middleware('guest')->name('password.reset');

The view should contain the email, password, password_confirmation, and (hidden) token fields. The token field should contain the value of secret $token received by the route.

Laravel Breeze defines the route in the routes/auth.php file and does the implementation in the app\Http\Controllers\Auth\NewPasswordController.php file.

Laravel reset password

 

Next, handle the password reset form submission.

use App\Models\User;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
 
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
                ? redirect()->route('login')->with('status', __($status))
                : back()->withErrors(['email' => [__($status)]]);
})->middleware('guest')->name('password.update');

The route validates the incoming request and updates the user's password in the database.

 

Summary

In this article, we have provided a comprehensive guide on implementing Laravel reset password functionality and sending reset password link emails in Laravel applications. We have covered essential steps and topics that ensure a seamless and secure password reset experience for your users.

The key topics we have covered in this guide are:

  1. Installing Laravel Breeze, a simple and user-friendly authentication scaffolding package, to lay the foundation for the Laravel reset password feature.
  2. Generating the authentication scaffolding, which includes pre-built views, controllers, and routes necessary for implementing the laravel reset password functionality.
  3. Configuring the mail settings in your Laravel application to enable the ability to send reset password link emails using Laravel's built-in mailing system.
  4. Migrating the database to set up the necessary tables and schema for user authentication and password reset.

By following this guide, you will learn how to create a robust Laravel reset password system and send reset password link emails in Laravel, ensuring a smooth and secure experience for your users. The knowledge gained from this tutorial will empower you to build user-friendly and secure password reset systems for your Laravel applications, enhancing the overall user experience and maintaining account security.

 

Steve Alila

He specializes in web design, WordPress development, and data analysis, with proficiency in Python, JavaScript, and data extraction tools. Additionally, he excels in web API development, AI integration, and data presentation using Matplotlib and Plotly. You can connect with him on LinkedIn or check his projects on GitHub page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment