Send Random Password To Email On New Registered User In Laravel 9
Hello guys! let’s create a new laravel project
GitHub Repo: send-random-password-to-email-laravel
composer create-project laravel/laravel SendRandomPass
Now, open the project folder in any code editor. Recommended IDE is PhpStorm
Add thedatabase credientials in .env file
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel # your database name
DB_USERNAME=root #your database username
DB_PASSWORD=password #your database password
Add the mail SMTP details in the .env file. Follow this tutorial to get Gmail SMTP server credentials Send Mail Using Gmail SMTP Server. But I’m using the Mailtrap SMTP server in this tutorial. So, You can follow this tutorial for Mailtrap SMTP Config Mailtrap in Laravel 8
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=abc123... # your mail username
MAIL_PASSWORD=abc123... # your mail password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=abc@example.com # your email
MAIL_FROM_NAME="${APP_NAME}"
Run this command to migrate all the tables into the MySQL database,
php artisan migrate
Now make a notification PasswordToUserEmail.php
// Command to make notification
php artisan make:notification PasswordToUserEmail// The notification will be generate in app/Notifications/
Write the below code inside PasswordToUserEmail.php
<?phpnamespace App\Notifications;use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;class PasswordToUserEmail extends Notification
{
use Queueable; private $password; /**
* Create a new notification instance.
*
* @return void
*/
public function __construct($password)
{
$this->password = $password;
} /**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['mail'];
} /**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line('Your password is: ' . $this->password)
->line('Note: This password is generated by the system!');
} /**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
Make a controller UserController.php
// Command to make controller
php artisan make:controller UserController// The controller will be generate in app/Http/Controllers/
Write the below code in UserController.php
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Notifications\PasswordToUserEmail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
class UserController extends Controller
{
function create()
{
return view('create-user');
}
function store(Request $request)
{
$request->validate(array(
'name' => ['required'],
'email' => ['email', 'unique:users,email'],
));
$password = Str::random(16);
$request['password'] = Hash::make($password);
$user = User::create($request->all());
$user->notify(new PasswordToUserEmail($password));
return redirect()->back();
}
}
Open the web.php file and add the following routes
<?phpuse Illuminate\Support\Facades\Route;Route::get('/', [\App\Http\Controllers\UserController::class, 'create'])->name('create');
Route::post('/store', [\App\Http\Controllers\UserController::class, 'store'])->name('store');
Now create a simple form to create a new user and send a password via email. Create a blade file in resources/views/create-user.blade.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Send Random Password To New Users</title>
</head>
<body>
<div class="w-50 container mt-5">
<form action="{{ route('store') }}" method="POST">
@csrf
<div class="form-group">
<label for="userName">Name</label>
<input type="text" name="name" class="form-control" id="userName" placeholder="Name...">
@error('name')
<strong class="text-danger">{{ $message }}</strong>
@enderror
</div>
<div class="form-group">
<label for="userEmail">Email</label>
<input type="email" name="email" class="form-control" id="userEmail" placeholder="Email...">
@error('email')
<strong class="text-danger">{{ $message }}</strong>
@enderror
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.14.7/dist/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
</body>
</html>
Everything is done :)
// Run this command the run the laravel project
php artisan serve