Introduction
In this tutorial, we will be creating a custom forgot and reset password system for a Laravel 10 application. We will be using the Laravel UI package to create the views and the Auth scaffolding to handle the authentication logic. We will also be using the Laravel Mail package to send out the reset password emails.
Prerequisites
Before we begin, you will need to have the following installed:
• PHP 7.4 or higher
• Composer
• Laravel 10
• A web server such as Apache or Nginx
• A database such as MySQL or PostgreSQL
Step 1: Install the Laravel UI Package
The first step is to install the Laravel UI package. This package provides the necessary views and authentication scaffolding for our application. To install it, run the following command in your terminal:
composer require laravel/ui
Step 2: Generate the Authentication Scaffolding
Once the Laravel UI package is installed, we can generate the authentication scaffolding. To do this, run the following command in your terminal:
php artisan ui:auth
This command will generate the necessary views and controllers for our authentication system.
Step 3: Configure the Mail Driver
Next, we need to configure the mail driver. This will allow us to send out reset password emails to our users. To do this, open the .env file and update the following lines:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.example.com
MAIL_PORT=587
MAIL_USERNAME=username
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls
Be sure to replace the example values with your own mail server credentials.
Step 4: Create the Reset Password Form
Next, we need to create the reset password form. To do this, create a new file called reset.blade.php in the resources/views/auth directory. Then, add the following code to the file:
@extends(‘layouts.app’)
@section(‘content’)
@endsection
This form will allow users to reset their passwords.
Step 5: Create the Reset Password Controller
Next, we need to create the ResetPasswordController. This controller will handle the logic for resetting the user’s password. To do this, run the following command in your terminal:
php artisan make:controller ResetPasswordController
Then, open the newly created ResetPasswordController.php file and add the following code:
with(
[‘token’ => $token, ’email’ => $request->email]
);
}
public function reset(Request $request)
{
$request->validate([
‘token’ => ‘required’,
’email’ => ‘required|email’,
‘password’ => ‘required|confirmed|min:8′,
]);
$response = Password::reset($request->only(’email’, ‘password’, ‘password_confirmation’, ‘token’), function ($user, $password) {
$user->password = bcrypt($password);
$user->save();
});
switch ($response) {
case Password::PASSWORD_RESET:
return redirect()->route(‘login’)->with(‘status’, ‘Your password has been reset!’);
default:
return back()->withErrors([’email’ => trans($response)]);
}
}
}
This controller will handle the logic for resetting the user’s password.
Step 6: Update the Routes
Next, we need to update the routes to use our new controller. To do this, open the routes/web.php file and update the following lines:
Route::get(‘password/reset’, ‘ResetPasswordController@showResetForm’)->name(‘password.reset’);
Route::post(‘password/reset’, ‘ResetPasswordController@reset’);
These routes will point to our new controller.
Step 7: Test the Reset Password System
Now that we have our custom reset password system set up, we can test it out. To do this, open your browser and navigate to the login page. Then, click the “Forgot Your Password?” link and enter your email address. You should then receive an email with a link to reset your password. Click the link and enter your new password. You should then be able to log in with your new password.
Conclusion
In this tutorial, we have created a custom forgot and reset password system for a Laravel 10 application. We have used the Laravel UI package to generate the authentication scaffolding and the Laravel Mail package to send out the reset password emails. We have also created a custom reset password form and controller to handle the reset password logic.
If you have created a custom login and registration system in the Laravel web application. And for this want to create a custom forget password and send a reset password link in an email system. Then this tutorial is for you only.
So, In this tutorial, you will learn how to create custom forget and send reset password links in an email with Laravel apps.
Laravel 10 Custom Reset & Forgot Password Tutorial
By using the following steps, you can create a custom forget and send reset password link in an email with Laravel apps:
- Step 1 – Create New Laravel 10 Project
- Step 2 – Configure Database & Mail with Laravel Project
- Step 3 – Define Routes
- Step 4 – Create Controller & Methods
- Step 5 – Create Blade Views
- Step 6 – Start Development Server
Step 1 – Create New Laravel 10 Project
First of all, Open your terminal or command prompt.
Then execute the following command into it to download and install fresh new laravel 10 setup:
composer create-project --prefer-dist laravel/laravel Blog
Step 2 – Configure Database & Mail with Laravel Project
Once you have installed Laravel app new setup. Now, you need to set up a database with laravel project.
Then visit your laravel app directory and open .env file. And then add database details like following:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=here your database name here DB_USERNAME=here database username here DB_PASSWORD=here database password here
Next, configure mail configuration in .env file like the following:
MAIL_MAILER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=bcca65cf7e165f MAIL_PASSWORD=c1abf6f6f9898d MAIL_ENCRYPTION=tls MAIL_FROM_ADDRESS="[email protected]" MAIL_FROM_NAME="${APP_NAME}"
Now, migrate the table into the database using the below command :
php artisan migrate
Step 3 – Define Routes
Once you set up database and mail smtp with Laravel project. Now you need to create custom routes for forget and reset password links in email.
So visit your laravel application directory and open routes/web.php file and add the following routes into it:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Auth\ForgotPasswordController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('forget-password', [ForgotPasswordController::class, 'showForgetPasswordForm'])->name('forget.password.get');
Route::post('forget-password', [ForgotPasswordController::class, 'submitForgetPasswordForm'])->name('forget.password.post');
Route::get('reset-password/{token}', [ForgotPasswordController::class, 'showResetPasswordForm'])->name('reset.password.get');
Route::post('reset-password', [ForgotPasswordController::class, 'submitResetPasswordForm'])->name('reset.password.post');
Step 4 – Create Controller and Method
Execute the following command on terminal or cmd to create controller file; which name ForgotPasswordController.php:
php artisan make:controller ForgotPasswordController
Then visit app/controllers/ directory and open ForgotPasswordController.php and update the below code in your controller:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;
use Carbon\Carbon;
use App\Models\User;
use Mail;
use Hash;
use Illuminate\Support\Str;
class ForgotPasswordController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function showForgetPasswordForm()
{
return view('auth.forgetPassword');
}
/**
* Write code on Method
*
* @return response()
*/
public function submitForgetPasswordForm(Request $request)
{
$request->validate([
'email' => 'required|email|exists:users',
]);
$token = Str::random(64);
DB::table('password_resets')->insert([
'email' => $request->email,
'token' => $token,
'created_at' => Carbon::now()
]);
Mail::send('email.forgetPassword', ['token' => $token], function($message) use($request){
$message->to($request->email);
$message->subject('Reset Password');
});
return back()->with('message', 'We have e-mailed your password reset link!');
}
/**
* Write code on Method
*
* @return response()
*/
public function showResetPasswordForm($token) {
return view('auth.forgetPasswordLink', ['token' => $token]);
}
/**
* Write code on Method
*
* @return response()
*/
public function submitResetPasswordForm(Request $request)
{
$request->validate([
'email' => 'required|email|exists:users',
'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required'
]);
$updatePassword = DB::table('password_resets')
->where([
'email' => $request->email,
'token' => $request->token
])
->first();
if(!$updatePassword){
return back()->withInput()->with('error', 'Invalid token!');
}
$user = User::where('email', $request->email)
->update(['password' => Hash::make($request->password)]);
DB::table('password_resets')->where(['email'=> $request->email])->delete();
return redirect('/login')->with('message', 'Your password has been changed!');
}
}
Step 5 – Create Blade views
Create auth folder inside resources/views/ folder and create a new layout.blade.php, login.blade.php file, forgetpassword.blade.php, and forgetPasswordLink.blade.php inside the resources/views/ Auth directory.
Firstly, you need to create layout.blade.php file inside resources/views/ Auth and update the below code into your file:
<!DOCTYPE html>
<html>
<head>
<title>Laravel - Tutsmake.com</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<style type="text/css">
@import url(https://fonts.googleapis.com/css?family=Raleway:300,400,600);
body{
margin: 0;
font-size: .9rem;
font-weight: 400;
line-height: 1.6;
color: #212529;
text-align: left;
background-color: #f5f8fa;
}
.navbar-laravel
{
box-shadow: 0 2px 4px rgba(0,0,0,.04);
}
.navbar-brand , .nav-link, .my-form, .login-form
{
font-family: Raleway, sans-serif;
}
.my-form
{
padding-top: 1.5rem;
padding-bottom: 1.5rem;
}
.my-form .row
{
margin-left: 0;
margin-right: 0;
}
.login-form
{
padding-top: 1.5rem;
padding-bottom: 1.5rem;
}
.login-form .row
{
margin-left: 0;
margin-right: 0;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light navbar-laravel">
<div class="container">
<a class="navbar-brand" href="#">Laravel</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
@guest
<li class="nav-item">
<a class="nav-link" href="{{ route('login') }}">Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ route('register') }}">Register</a>
</li>
@else
<li class="nav-item">
<a class="nav-link" href="{{ route('logout') }}">Logout</a>
</li>
@endguest
</ul>
</div>
</div>
</nav>
@yield('content')
</body>
</html>
Then create forgetPassword.blade.php file inside resources/views/ Auth and update the below code into your file
@extends('layout')
@section('content')
<main class="login-form">
<div class="cotainer">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Reset Password</div>
<div class="card-body">
@if (Session::has('message'))
<div class="alert alert-success" role="alert">
{{ Session::get('message') }}
</div>
@endif
<form action="{{ route('forget.password.post') }}" method="POST">
@csrf
<div class="form-group row">
<label for="email_address" class="col-md-4 col-form-label text-md-right">E-Mail Address</label>
<div class="col-md-6">
<input type="text" id="email_address" class="form-control" name="email" required autofocus>
@if ($errors->has('email'))
<span class="text-danger">{{ $errors->first('email') }}</span>
@endif
</div>
</div>
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Send Password Reset Link
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</main>
@endsection
Then create forgetPasswordLink.blade.php file inside resources/views/ Auth and update the below code into your file
@extends('layout')
@section('content')
<main class="login-form">
<div class="cotainer">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Reset Password</div>
<div class="card-body">
<form action="{{ route('reset.password.post') }}" method="POST">
@csrf
<input type="hidden" name="token" value="{{ $token }}">
<div class="form-group row">
<label for="email_address" class="col-md-4 col-form-label text-md-right">E-Mail Address</label>
<div class="col-md-6">
<input type="text" id="email_address" class="form-control" name="email" required autofocus>
@if ($errors->has('email'))
<span class="text-danger">{{ $errors->first('email') }}</span>
@endif
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">Password</label>
<div class="col-md-6">
<input type="password" id="password" class="form-control" name="password" required autofocus>
@if ($errors->has('password'))
<span class="text-danger">{{ $errors->first('password') }}</span>
@endif
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">Confirm Password</label>
<div class="col-md-6">
<input type="password" id="password-confirm" class="form-control" name="password_confirmation" required autofocus>
@if ($errors->has('password_confirmation'))
<span class="text-danger">{{ $errors->first('password_confirmation') }}</span>
@endif
</div>
</div>
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Reset Password
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</main>
@endsection
Next, visit to resources/views/auth/ directory and create login.blade.php file. And add the following code into it:
@extends('layout')
@section('content')
<main class="login-form">
<div class="cotainer">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Login</div>
<div class="card-body">
<form action="{{ route('login.post') }}" method="POST">
@csrf
<div class="form-group row">
<label for="email_address" class="col-md-4 col-form-label text-md-right">E-Mail Address</label>
<div class="col-md-6">
<input type="text" id="email_address" class="form-control" name="email" required autofocus>
@if ($errors->has('email'))
<span class="text-danger">{{ $errors->first('email') }}</span>
@endif
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">Password</label>
<div class="col-md-6">
<input type="password" id="password" class="form-control" name="password" required>
@if ($errors->has('password'))
<span class="text-danger">{{ $errors->first('password') }}</span>
@endif
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember"> Remember Me
</label>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="checkbox">
<label>
<a href="{{ route('forget.password.get') }}">Reset Password</a>
</label>
</div>
</div>
</div>
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Login
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</main>
@endsection
Next, visit to resources/views/email/ directory and create forgetPassword.blade.php file. And add the following code into it:
<h1>Forget Password Email</h1> You can reset password from bellow link: <a href="{{ route('reset.password.get', $token) }}">Reset Password</a>
Step 6 – Start Development Server
To start the development server. So, execute the PHP artisan serve command on the terminal and start your server:
php artisan serve
If you want to run the project diffrent port so use this below command
php artisan serve --port=8080
Now you are ready to run our example by opening this url in browser:
http://127.0.0.1:8000/forget-password
Conclusion
That’s it, In this tutorial, you have learned how to create custom forget and send reset password links in an email with Laravel apps.