How to customize the email verification email from Laravel 5.7? - laravel-5

I just upgraded to Laravel 5.7 and now I am using the built in Email Verification. However there is 2 things I have not been able to figure out and the primary issue is how can I customize the email that is being sent to the user for verifying their email? I also can't figure out how to initiate sending that email if the users changes their email but I can save that for another thread.

When you want to add Email Verification in Laravel 5.7 the suggested method is to implement Illuminate\Contracts\Auth\MustVerifyEmail and use the Illuminate\Auth\MustVerifyEmail trait on the App\User Model.
To make some custom behaviour you can override the method sendEmailVerificationNotification which is the method that notifies the created user by calling the method notify, and passes as a parameter a new instance of the Notifications\MustVerifyEmail class.
You can create a custom Notification which will be passed as a parameter to the $this->notify() within the sendEmailVerificationNotification method in your User Model:
public function sendEmailVerificationNotification()
{
$this->notify(new App\Notifications\CustomVerifyEmail);
}
...then in your CustomVerifyEmail Notification you can define the way the verification will be handled. You can notify created user by sending an email with a custom verification.route which will take any parameters that you want.
Email verification notification process
When a new user signs-up an Illuminate\Auth\Events\Registered Event is emitted in the App\Http\Controllers\Auth\RegisterController and that Registered event has a listener called Illuminate\Auth\Listeners\SendEmailVerificationNotification which is registered in the App\Providers\EventServiceProvider:
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
]
];
The SendEmailVerificationNotification listener checks if the $user – which is passed as a parameter to new Registered($user = $this->create($request->all())) in the Laravel default authentication App\Http\Controllers\Auth\RegisterController – is an instance of Illuminate\Contracts\Auth\MustVerifyEmail which is the name of the trait that Laravel suggests is used in the App\User Model when you want to provide default email verification and also check that $user is not already verified. If all that passes, the sendEmailVerificationNotification method is called on that user:
if ($event->user instanceof MustVerifyEmail && !$event->user->hasVerifiedEmail()) {
$event->user->sendEmailVerificationNotification();
}

I think the simple way to do this is to make a new notification using the docs here: https://laravel.com/docs/5.7/notifications#creating-notifications
Then override the function:
public function sendEmailVerificationNotification()
{
$this->notify(new App\Notifications\CustomEmailNotification);
}
In the users model.
Or you can
php artisan vendor:publish --tag=laravel-notifications
This will copy the templates to the resources/views/vendor/notifications directory and you can modify them there

Unfortunately this email that is sent out is not from a "view", it is a Notification that is built inline actually. This is where it is currently built when needing to be sent off: Illuminate\Auth\Notifications\VerifyEmail#toMail. This particular class has a static callback that can be set to build this email instead of letting it do it.
In a Service Provider in the boot method you will need to assign a callback for this class:
Something "like" this might work:
public function boot()
{
\Illuminate\Auth\Notifications\VerifyEmail::toMailUsing(function ($notifiable) {
// this is what is currently being done
// adjust for your needs
return (new \Illuminate\Notifications\Messages\MailMessage)
->subject(\Lang::getFromJson('Verify Email Address'))
->line(\Lang::getFromJson('Please click the button below to verify your email address.'))
->action(
\Lang::getFromJson('Verify Email Address'),
$this->verificationUrl($notifiable)
)
->line(\Lang::getFromJson('If you did not create an account, no further action is required.'));
});
}
As this is a notification you should have more options on customizing it.
If you want to use your own Notification class you can override the sendEmailVerificationNotification method on the User (Authenticatable) model (this is from the MustVerifyEmail trait).
Second Question:
The VerificationController (App\Http\Controllers\Auth\VerificationController) that you should have has a method named resend (from the trait VerifiesEmails) that looks like a good candidate for this purpose.
You should have routes setup for these verification routes via Auth::routes(['verify' => true]);
Note:
The verification system uses a field on the users table email_verified_at in 5.7 to mark this. You would want to make sure you have this field. When the user changes email address I suppose you could make this null then redirect them to the resend route, to send off the new verification. This will put them into an "unverified" state though until they reverify, if that is what you intend to happen.
Update:
Seems we were going down the right track. I found this SO answer that goes over similar things:
Changing the default “subject” field for the verification email in laravel 5.7

For quick and easy way:
php artisan vendor:publish --tag=laravel-notifications
It's creating a new file in:
\resources\views\vendor\notifications
This is Laravel's email themplate. You can change and customize it.

I'll show you how to customize User verification email using custom view from scratch without using any vendor publish
Step: 1
Create a new notification UserVerifyNotification class. It should extend the VerifyEmail class from the library Illuminate\Auth\Notifications\VerifyEmail;
Code :
use Illuminate\Auth\Notifications\VerifyEmail;
...
class UserVerifyNotification extends VerifyEmail implements ShouldQueue
{
use Queueable;
public $user; //you'll need this to address the user
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($user='')
{
$this->user = $user ?: Auth::user(); //if user is not supplied, get from session
}
/**
* 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)
{
$actionUrl = $this->verificationUrl($notifiable); //verificationUrl required for the verification link
$actionText = 'Click here to verify your email';
return (new MailMessage)->subject('Verify your account')->view(
'emails.user-verify',
[
'user'=> $this->user,
'actionText' => $actionText,
'actionUrl' => $actionUrl,
]);
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
Step:2
Create the blade view for the email (user-verify.blade.php) inside resources\views\emails
<DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
</head>
<body>
<p>Dear {{$user->name}},</p>
<p>
Please click the button below to verify your email address.
</p>
{{$actionText}}
<p>If you did not create an account, no further action is required.</p>
<p>
Best regards, <br>
{{ config('app.name')}}
</p>
<p>
<hr>
<span class="break-all">
<strong>If you’re having trouble clicking the link, copy and paste the URL below into your web browser:</strong><br/>
<em>{{$actionUrl}}</em>
</p>
</body>
</html>
Step:3
Add the following method inside the User model
class User extends Authenticatable implements MustVerifyEmail
{
use HasFactory, Notifiable;
...
...
...
public function sendEmailVerificationNotification()
{
$this->notify(new \App\Notifications\UserVerifyNotification(Auth::user())); //pass the currently logged in user to the notification class
}
}
Explanation
When a new user is registered, the Registered event (Illuminate\Auth\Events) is called.
There is a listener inside EventServiceProvider (App\Providers\EventServiceProvider) that listens to the Registered event. 1. Once registration is completed, it calls SendEmailVerificationNotification method (Illuminate\Auth\Listeners\SendEmailVerificationNotification).
The listener (step-2) calls the sendEmailVerificationNotification() method from the library Illuminate\Auth\Listeners\SendEmailVerificationNotification
We now override the sendEmailVerificationNotification() function in Step: 3 and indicate that we would like to use our own notification class which we made earlier in Step: 1
The notification class gets the 'verification link' and calls the 'user-verify' blade to send email with the necessary link as defined in Step: 2
You'll need to add routes required for verification. Just add the following route in the web.php file
Auth::routes([
'verify' => true,
'register' => true,
]);

Building slightly on the answer by Andrew Earls, you can also publish all the markdown mail components used by the application with this command:
php artisan vendor:publish --tag=laravel-mail
Once that's done you'll have a series of html and markdown files to modify in resources/views/vendor/mail. This will allow you to modify the overall email layout and also 'theme' the CSS. I'd highly recommend having a good read of the Mail docs - Customizing The Components.
CSS theming
As a general email theming quick-start (Laravel 5.7), you can:
Publish the theme with php artisan vendor:publish --tag=laravel-mail .
Copy resources/views/vendor/mail/html/themes/default.css to your own file. e.g resources/views/vendor/mail/html/themes/wayne.css
Edit config/mail.php and where you see 'theme' => 'default' change it to 'theme' => 'wayne'
Edit wayne.css to restyle your emails.
Hope that helps someone.

To send verification email you can just use the next code:
// send new verification email to user
$user->sendEmailVerificationNotification();

In Route File
Auth::routes(['verify' => true]);
In AppServiceProvider.php File
namespace App\Providers;
use App\Mail\EmailVerification;
use Illuminate\Support\ServiceProvider;
use View;
use URL;
use Carbon\Carbon;
use Config;
use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Notifications\Messages\MailMessage;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
// Override the email notification for verifying email
VerifyEmail::toMailUsing(function ($notifiable){
$verifyUrl = URL::temporarySignedRoute('verification.verify',
\Illuminate\Support\Carbon::now()->addMinutes(\Illuminate\Support\Facades
\Config::get('auth.verification.expire', 60)),
[
'id' => $notifiable->getKey(),
'hash' => sha1($notifiable->getEmailForVerification()),
]
);
return new EmailVerification($verifyUrl, $notifiable);
});
}
}
Now Create EmailVerification With Markdown
php artisan make:mail EmailVerification --markdown=emails.verify-email
Edit The EmailVerrification as you want and the blade file
class EmailVerification extends Mailable
{
use Queueable, SerializesModels;
public $verifyUrl;
protected $user;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($url,$user)
{
$this->verifyUrl = $url;
$this->user = $user;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$address = 'mymail#gmail.com';
$name = 'Name';
$subject = 'verify Email';
return $this->to($this->user)->subject($subject)->from($address, $name)->
markdown('emails.verify',['url' => $this->verifyUrl,'user' => $this->user]);
}
}
in the blade file change the design as you want and use verifyUrl to display the verification link and $user to display user information
thanks, happy coding :)

Navigate to these files
vendor/laravel/framework/src/Illuminate/Auth/MustVerifyEmail.php
vendor/laravel/framework/src/Illuminate/Auth/Notifications/VerifyEmail.php
and then customize it.
you can even introduce a constructor in
vendor/laravel/framework/src/Illuminate/Auth/Notifications/VerifyEmail.php
and pass value through vendor/laravel/framework/src/Illuminate/Auth/MustVerifyEmail.php
eg:

Related

How to add a mailing feature on laravel 8

I am taking over a project and a client wants me to add a mailing feature like a gmail with inbox, sent messages and the user can also reply to emails from outside the system and the people receiving it can also reply. I have basic knowledge on laravel but this is my first time creating a feature like this can anyone give a stepping stone. This project has a VUE.js as a front end and a laravel as an API
Step -1: Create a Mail using,
php artisan make:mail MailName
Check the file MailName.php inside App/Mail/ directory
Step - 2: Create a function to send the email with the requested data.
public function sendMail(Request $request){
$data = [
'value1'=> $request->value1,
'value2'=> $request->value2,
'value3'=> $request->value3
];
//You can add any function like storing the values into db.
if(someconditions){
\Mail::to('emailid#domainname.com')->send(new MailName($data));
return back()->with('success', 'Email has been sent successfully!');
}
else
{
return back()->with('error', 'Something went wrong!');
}
}
Step - 3: Open the App/Mail/MailName.php
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
use Illuminate\Mail\Mailables\Address;
//You can include your model here.
class DeleteResponseMail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public $data;
public function __construct($data)
{
$this->data = $data;
}
/**
* Get the message envelope.
*
* #return \Illuminate\Mail\Mailables\Envelope
*/
public function envelope()
{
return new Envelope(
from: new Address('fromemail#somedomain.com', 'From Email Name'),
replyTo: [
new Address('admin#yourdomain.com', 'Your email name'),
],
subject: 'Email Subject',
);
}
/**
* Get the message content definition.
*
* #return \Illuminate\Mail\Mailables\Content
*/
public function content()
{
return new Content(
view: 'emails.mail',
);
}
/**
* Get the attachments for the message.
*
* #return array
*/
public function attachments()
{
return [];
}
}
Step - 4: Create mail.blade.php under resources/views/emails
Hi $data['value1'],
We have received your application. Thanks!
Step - 5: Open your .env file and add the email configurations.
MAIL_MAILER=enteryourmailerhere (ex.smtp)
MAIL_HOST=enteryourmailhosthere (ex.smtp.gmail.com)
MAIL_PORT=entertheport (ex. 25)
MAIL_USERNAME=emailid#yourdomain.com
MAIL_PASSWORD=emailpassword
MAIL_ENCRYPTION=""
MAIL_FROM_ADDRESS="fromemail#yourdomain.com"
MAIL_FROM_NAME="${APP_NAME}"
That's all! It should work.

SMTP: Change Message-ID domain in sending emails from Laravel 5.7 (Swift Mailer)

Laravel 5.7 sends emails using Swift Mailer.
By default, all sent emails will have the Message-ID header with the domain swift.generated (eg. Message-ID: <90b9835f38bb441bea134d3ac815dd6f#swift.generated>).
I would like to change the domain swift.generated to for example my-domain.com.
How can I change this for all emails?
Edit the file config/mail.php and define your domain near the end:
'domain' => 'yourdomain.com',
In the command line, create a new listener:
php artisan make:listener -e 'Illuminate\Mail\Events\MessageSending' MessageSendingListener
Edit the newly created listener and make it look as follows (do NOT implement ShouldQueue):
<?php
/**
* Set the domain part in the message-id generated by Swift Mailer
*/
namespace App\Listeners;
use Illuminate\Mail\Events\MessageSending;
use Swift_Mime_IdGenerator;
class MessageSendingListener
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* #param MessageSending $event
* #return void
*/
public function handle(MessageSending $event)
{
$event->message->setId((new Swift_Mime_IdGenerator(config('mail.domain')))->generateId());
}
}
Register the listener in app/Providers/EventServiceProvider:
protected $listen = [
// [...]
\Illuminate\Mail\Events\MessageSending::class => [
\App\Listeners\MessageSendingListener::class,
],
];
That's it, enjoy! :)
Just found a correct way to change #swift.generated in message ID.
Add this code to your AppServiceProvider->boot() method:
\Swift_DependencyContainer::getInstance()
->register('mime.idgenerator.idright')
->asValue(config('mail.domain'));
config('mail.domain') is a custom config entry so you can change it to whatever you want.
Tested in Laravel 6, maybe will work with 5.* versions too.
Also you can find many interesting configs in this file:
vendor/swiftmailer/swiftmailer/lib/dependency_maps/mime_deps.php

Laravel Email Verification Template Location

I have been reading from the documentation about the new feature of laravel the email verification. Where can I locate the email template that is sent to the user? It does not show here: https://laravel.com/docs/5.7/verification#after-verifying-emails
Laravel uses this method of VerifyEmail notification class for send email:
public function toMail($notifiable)
{
if (static::$toMailCallback) {
return call_user_func(static::$toMailCallback, $notifiable);
}
return (new MailMessage)
->subject(Lang::getFromJson('Verify Email Address'))
->line(Lang::getFromJson('Please click the button below to verify your email address.'))
->action(
Lang::getFromJson('Verify Email Address'),
$this->verificationUrl($notifiable)
)
->line(Lang::getFromJson('If you did not create an account, no further action is required.'));
}
Method in source code.
If you wanna use your own Email template, you can extend Base Notification Class.
1) Create in app/Notifications/ file VerifyEmail.php
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Lang;
use Illuminate\Auth\Notifications\VerifyEmail as VerifyEmailBase;
class VerifyEmail extends VerifyEmailBase
{
// use Queueable;
// change as you want
public function toMail($notifiable)
{
if (static::$toMailCallback) {
return call_user_func(static::$toMailCallback, $notifiable);
}
return (new MailMessage)
->subject(Lang::getFromJson('Verify Email Address'))
->line(Lang::getFromJson('Please click the button below to verify your email address.'))
->action(
Lang::getFromJson('Verify Email Address'),
$this->verificationUrl($notifiable)
)
->line(Lang::getFromJson('If you did not create an account, no further action is required.'));
}
}
2) Add to User model:
use App\Notifications\VerifyEmail;
and
/**
* Send the email verification notification.
*
* #return void
*/
public function sendEmailVerificationNotification()
{
$this->notify(new VerifyEmail); // my notification
}
Also if you need blade template:
laravel will generate all of the necessary email verification views
when the make:auth command is executed. This view is placed in
resources/views/auth/verify.blade.php. You are free to customize
this view as needed for your application.
Source.
Answer in comment already. Sent by the toMail() method.
vendor\laravel\framework\src\Illuminate\Auth\Notifications\VerifyEmail::toMail();
For template structure and appearance; take a look at this locations also and you can also publish to modify the template:
\vendor\laravel\framework\src\Illuminate\Notifications\resources\views\email.blade.php
\vendor\laravel\framework\src\Illuminate\Mail\resources\views\
To publish those locations:
php artisan vendor:publish --tag=laravel-notifications
php artisan vendor:publish --tag=laravel-mail
After running this command, the mail notification templates will be located in the resources/views/vendor directory.
Colors and style are controlled by the CSS file in resources/views/vendor/mail/html/themes/default.css
Also, if you want to translate standard mail VerifyEmail (or other where use Lang::fromJson(...)), you need create new json file in resources/lang/ and name it ru.json, for example.
It may contain (resources/lang/ru.json) text below and must be valid.
{
"Verify Email Address" : "Подтверждение email адреса"
}
Actually they do not use any blade or template files. They create notifications and write code for it in notifications.
Look I do that very easy
do the following steps :
In Route File
Auth::routes(['verify' => true]);
In AppServiceProvider.php File
namespace App\Providers;
use App\Mail\EmailVerification;
use Illuminate\Support\ServiceProvider;
use View;
use URL;
use Carbon\Carbon;
use Config;
use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Notifications\Messages\MailMessage;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
// Override the email notification for verifying email
VerifyEmail::toMailUsing(function ($notifiable){
$verifyUrl = URL::temporarySignedRoute('verification.verify',
\Illuminate\Support\Carbon::now()->addMinutes(\Illuminate\Support\Facades
\Config::get('auth.verification.expire', 60)),
[
'id' => $notifiable->getKey(),
'hash' => sha1($notifiable->getEmailForVerification()),
]
);
return new EmailVerification($verifyUrl, $notifiable);
});
}
}
Now Create EmailVerification With Markdown
php artisan make:mail EmailVerification --markdown=emails.verify-email
Edit The EmailVerrification as you want and the blade file
class EmailVerification extends Mailable
{
use Queueable, SerializesModels;
public $verifyUrl;
protected $user;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($url,$user)
{
$this->verifyUrl = $url;
$this->user = $user;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$address = 'mymail#gmail.com';
$name = 'Name';
$subject = 'verify Email';
return $this->to($this->user)->subject($subject)->from($address, $name)->
markdown('emails.verify',['url' => $this->verifyUrl,'user' => $this->user]);
}
}
in the blade file change the design as you want and use verifyUrl to display the verification link and $user to display user information
thanks, happy coding :)
vendor\laravel\framework\src\Illuminate\Mail\resources\views\html
You will find the Laravel default email template in this file location.
If a notification supports being sent as an email, you should define a toMail method on the notification class. This method will receive a $notifiable entity and should return a Illuminate\Notifications\Messages\MailMessage instance. Mail messages may contain lines of text as well as a "call to action".
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
$url = url('/invoice/'.$this->invoice->id);
return (new MailMessage)
->greeting('Hello!')
->line('One of your invoices has been paid!')
->action('View Invoice', $url)
->line('Thank you for using our application!');
}
You can use the laravel e-mail builder as documented here: https://laravel.com/docs/5.8/notifications#mail-notifications. Laravel will take care of the e-mail view.

How to prevent access to Model by id with JWTAuth and Laravel?

I'm building some API endpoints with Laravel, and I'm using JWTAuth as the token provider for authorizing requests.
I've gotten the setup to protect a group of API routes that works correctly using:
Route::group(['prefix' => '/v1', 'middleware' => 'jwt.auth'], function() {
Route::resource('messages', 'MessagesController');
});
The Message model belongs to a User
I'm attempting to perform some requests using that relationship while keeping the request from providing data that didn't belong to the user:
Get a list of the logged in user's messages
Get an individual message of the logged in user
The main question I have is how to prevent the user from accessing a Message that does not belong to them. I have this in my controller:
public function show($message_id)
{
$message = Message::findOrFail($message_id);
return $message;
}
That obviously will return the Message regardless of whether or not it belongs to that user. Any suggestions on how to improve that to restrict accessing other user's messages?
For the listing of all messages, I was able to do the following in the controller:
public function index()
{
$user_id = Auth::User()->id;
$messages = Message::where('user_id', $user_id)->paginate(10);
return $messages;
}
This works, but I'm not sure this is the best way to do it. Maybe it is, but some feedback would be appreciated. I'm confused as to whether or not the middleware should be handling what the user has access to or if it should be part of the eloquent query?
Your question is,
how to prevent the user from accessing a Message that does not belong
to them.
Thats falls under Authorization
You can use Gates to Authorize users and I think it's the best approach here. Fist of all you'd need a Policy object.
<?php
namespace App\Policies;
use App\User;
use App\Message;
class MessagePolicy
{
/**
* Determine if the given Message can be viewed by the user.
*
* #param \App\User $user
* #param \App\Message $Message
* #return bool
*/
public function view(User $user, Message $Message)
{
return $user->id === $Message->user_id;
// Here this User's id should match with the user_id of the Massage
}
}
You can even generate the boilerplate like this,
php artisan make:policy MessagePolicy --model=Message
Then you can register it in your AuthServiceProvider like this,
<?php
namespace App\Providers;
use App\Message;
use App\Policies\MessagePolicy;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
Message::class => MessagePolicy::class,
];
/**
* Register any application authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
Gate::define('view-message', 'MessagePolicy#view');
}
}
And in your Controller you can use it like this,
public function show($message_id)
{
if (Gate::allows('view-message', Message::findOrFail($message_id)) {
return $message;
}
}
Note: Please use this code snippet as a reference or a starting point since I haven't tested it properly. But underlying concept is correct. Use this as pseudocode. If something wrong found, please update it here :)

replace password reset mail template with custom template laravel 5.3

I did the laravel command for authentication system , php artisan make:auth it made the authentication system for my app and almost everything is working.
Now when i use the forgot password and it sends me a token to my mail id , i see that the template contains laravel and some other things that i might wanna edit or ommit, to be precise , i want my custom template to be used there.
I looked up at the controllers and their source files but i can't find the template or the code that is displaying the html in the mail.
How do i do it ?
How do i change it?
This is the default template that comes from laravel to the mail.
Just a heads up: In addition to the previous answer, there are additional steps if you want to modify the notification lines like You are receiving this..., etc. Below is a step-by-step guide.
You'll need to override the default sendPasswordResetNotification method on your User model.
Why? Because the lines are pulled from Illuminate\Auth\Notifications\ResetPassword.php. Modifying it in the core will mean your changes are lost during an update of Laravel.
To do this, add the following to your your User model.
use App\Notifications\PasswordReset; // Or the location that you store your notifications (this is default).
/**
* Send the password reset notification.
*
* #param string $token
* #return void
*/
public function sendPasswordResetNotification($token)
{
$this->notify(new PasswordReset($token));
}
Lastly, create that notification:
php artisan make:notification PasswordReset
And example of this notification's content:
/**
* The password reset token.
*
* #var string
*/
public $token;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($token)
{
$this->token = $token;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Build the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line('You are receiving this email because we received a password reset request for your account.') // Here are the lines you can safely override
->action('Reset Password', url('password/reset', $this->token))
->line('If you did not request a password reset, no further action is required.');
}
Run the following command in the terminal and the two email templates will be copied to your resources/vendor/notifications folder. Then you can modify the templates.
php artisan vendor:publish --tag=laravel-notifications
You can read more about Notifications in Laravel Docs.
If you wish to modify the mail template then check Laravel markdown, here you can change the default mail template:
if you do want to get HTML and be able to edit it, run this:
php artisan vendor:publish --tag=laravel-mail
This will happen:
Copied Directory
[/vendor/laravel/framework/src/Illuminate/Mail/resources/views] To
[/resources/views/vendor/mail]
Resource: https://laraveldaily.com/mail-notifications-customize-templates/
I ended up using Mail facade in User model..
public function sendPasswordResetNotification($token){
// $this->notify(new MyCustomResetPasswordNotification($token)); <--- remove this, use Mail instead like below
$data = [
$this->email
];
Mail::send('email.reset-password', [
'fullname' => $this->fullname,
'reset_url' => route('user.password.reset', ['token' => $token, 'email' => $this->email]),
], function($message) use($data){
$message->subject('Reset Password Request');
$message->to($data[0]);
});
}
in .env file or config/app.php file you have to change your app name and it's working fine.
You can also achieve this by building your own mail template and sending the Reset link yourself using the php mail() or or Laravel Mail Facade but first you will need to create the reset token
1) use Illuminate\Contracts\Auth\PasswordBroker;
$user = User::where('email', $email)->first();
if ($user) {
//so we can have dependency
$password_broker = app(PasswordBroker::class);
//create reset password token
$token = $password_broker->createToken($user);
DB::table('password_resets')->insert(['email' => $user->email, 'token' => $token, 'created_at' => new Carbon]);
//Send the reset token with your own template
//It can be like $link = url('/').'/password/reset/'.$token;
}

Resources