Send email notification in Laravel 5.6

email verification

Notification is one of the best features in Laravel which was introduced in Laravel 5.3 and later. This feature allows us to send notification of events to the user. We can send notification through emails, SMS, and Slack. Also, notifications can be stored in our database that can be accessed later.

In this article, we will implement this email notification feature of laravel in our project. We will send a welcome message to the user through email notification. Let’s start coding!

Project Setup

You can start with the fresh installation of laravel or with an existing project.
Database
For database setup, just create a database and configure .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=kodementor
DB_USERNAME=root
DB_PASSWORD=secret

Email
For testing purpose, we will use mailtrap.io. If you are not familiar with this, just go to mailtrap.io and register your account. After registration, you will get username and password. After it, configure your .env file.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=fc9a75s7e48a54a
MAIL_PASSWORD=131ea2f702b46f4
MAIL_ENCRYPTION=null

Authentication
We will use laravel default authentication for our project. We will create authentication scaffolding using following artisan command:

php artisan make:auth

Create Notification

As said earlier, we will send welcome email to the user after registration. For this, we create a new notification with artisan command:

php artisan make:notification AccountCreated

This will create a new file AccountCreated in App/Notification/ directory. If you dig into that file, you need to note two methods i.e. via method and toMail method.

The via method is used to determine which channels the notification will be delivered like emails, SMS and Slack.

The toMail method is used to send notification through email. Similar this this, you may add toDatabase. This acts as a API for rapidly building emails. It encapsulates the entire process of building an email template. It has different calls like subject, greeting, level, line, action and salutation.

We will change this file so that it sends an email that looks like a welcome email. So, our final code looks like below:

user = $user;
    }

    /**
     * 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)
            ->subject('Account Created in KodeMentor') // Subject of email
            ->greeting('Hello '.$this->user->name) // Greeting to User like: Dear Sir, Hello Madam, etc ...
            // ->level('info')// what kind of email. Available options: info, success, error. Default: info
            ->line('Welcome to KodeMentor. We are glad to have you on board.') //email body
            ->action('Browse Articles', url('https://kodementor.com/'))  //button in email
            ->line('Thank you for using our application!');
            // ->salutation('')  // example: best regards, thanks, etc ...
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

Configure Model

To use notification, respective model should use Notifiable trait. Since, we are using User model to send notification, we will have default setup for this. So, we don’t need to change anything. But, if you intend to use in other model (which we should do), you should user Notifiable trait.

Firing Notification

Now, it's time to fire our notification. We will fire notification from RegisterController afte user detail has been saved to database. We can fire notification using notify method.

use App\Notifications\AccountCreated;

$user->notify(new AccountCreated($user));

We can also fire using Notification Facade. This is useful primarily when you need to send a notification to multiple notifiable entities such as a collection of users.

use App\Notifications\AccountCreated;

Notification::send($users, new ArticlePublished($article));

Since, we will fire this notification after user is created, we need to modify our create method only. Thus, our create method in RegisterController.php looks like below:

// App/Http/Controllers/Auth/RegisterController.php

// don't forget to import AccountCreated class
// by using "use App\Notifications\AccountCreated;" on top

protected function create(array $data)
{
    $user = User::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => bcrypt($data['password']),
            ]);

    $user->notify(new AccountCreated($user));

    return $user;
}

Testing

Now, our application is ready to fire notification. Let's test our application by creating new user.
Send email notification in Laravel 5.6

After the user has been created, we will get an email notification:
Send email notification in Laravel 5.6

Additional Configurations

Here are some of the additonal features we can add to this notification.

Queuing Notification
Similar to jobs, we can put our notification in queue. For this, we need to implement ShouldQueue interface and Queueable trait. For example:

The default email template we are using is notifications/emails.php. If you wish to customize your own email template, you can publish email template and modify as per your requirements. To publish it, run the below artisan command:

php artisan vender:publish

This will publish your email.php template in resources/views/vendor/notifications/ directory. You can change this file and test.

Conclusion

This is all for email notification in laravel. I hope you have got a clear idea about notification. In the next article, we will talk about sending notification through slack. Thank you for reading this article. If you have any comment or feedback, please feel free to drop a comment.

Read More Articles

102 COMMENTS

  1. I like the helpful information you supply on your articles.
    I will bookmark your weblog and test once more right here regularly.

    I’m quite sure I will learn lots of new stuff
    proper here! Best of luck for the following!

  2. Everything is very open with a very clear explanation of the issues.
    It was really informative. Your site is very useful. Thanks for sharing!

  3. Hello there I am so glad I found your web site, I really found you by
    error, while I was browsing on Bing for something else, Anyways I am here now
    and would just like to say thanks for a remarkable post
    and a all round thrilling blog (I also love the theme/design),
    I don’t have time to read through it all at the moment but I have bookmarked it and also added your RSS feeds,
    so when I have time I will be back to read a lot more, Please do keep up the awesome job.

  4. Like all fields, photography, professional photography at that, is not as
    easy as you cann think. Then we go forward five weeks and Amelia
    actually starts to doubt there’s wrong while using baby.
    The mention oof Bro-step and American expansion of the genre is undeniable within tthe first sort context.

  5. I ljke the helpful info youu provide in your articles.
    I’ll bookmark your blog and check again here frequently.

    I’m quite certain I will learn many new stuff right here!
    Best of luck for the next!

  6. Right here is the perfect web site for anybody who wants to understand this topic.
    You realize a whole lot its almost hard to argue with you (not that I really will
    need to…HaHa). You certainly put a brand new spin on a topic
    that’s been discussed for many years. Great stuff, just wonderful!

  7. Write more, thats all I have to say. Literally,
    it seems as though you relied on the video to make your point.
    You definitely know what youre talking about, why waste your intelligence on just posting videos
    to your site when you could be giving us something informative to read?

  8. With havin so much written content do you ever run into any
    problems of plagorism or copyright infringement? My website
    has a lot of unique content I’ve either written myself or
    outsourced but it seems a lot of it is popping it up all over the web without my authorization. Do you know any solutions to help
    stop content from being stolen? I’d truly appreciate it.

  9. I’m гeaⅼly impressed with your wrіting ѕkillѕ andd also with thhe format in yoᥙr wеbⅼog.
    Is this а paid thеme or ddid you customize it yourself?
    Anyway keeр up the excellent high quality wгiting,
    it’s rare to sеe a grеat weblog like this one nowadays..

  10. I have been exploring for a little bit for any high quality articles or weblog posts on this kind of area .
    Exploring in Yahoo I eventually stumbled upon this website.
    Reading this information So i am satisfied
    to exhibit that I’ve a very just right uncanny
    feeling I found out just what I needed. I most indisputably will make certain to do not overlook this web site
    and provides it a glance on a constant basis.

  11. Hey! This post couldn’t be written any better! Reading this post reminds me of my previous room mate!
    He always kept talking about this. I will forward this article to him.
    Pretty sure he will have a good read. Thank you for sharing!

  12. I just like the helpful information you provide on your articles.
    I will bookmark your weblog and take a look at again here regularly.

    I am quite sure I will be informed a lot of new stuff proper here!
    Best of luck for the next!

  13. Simply want to say your article is as surprising.

    The clarity in your post is just spectacular and that i could assume you’re an expert in this subject.
    Fine with your permission allow me to take hold of your feed to
    stay updated with approaching post. Thanks 1,000,000 and please continue the rewarding work.

  14. Greetings! Quick question that’s completely off topic.
    Do you know how to make your site mobile friendly?

    My weblog looks weird when browsing from my iphone 4.
    I’m trying to find a template or plugin that might
    be able to correct this issue. If you have any recommendations, please share.
    Thank you!

  15. Hi, і think that i noticed youu visited my weblog so i
    came to return the desiгe?.I’m attempting to to find іssues to enhаnce my webѕite!I suppose
    its аdequate to uѕe sоme off youyr ideas!!

  16. Hey! I could have sworn I’ve been to this blog before but after checking
    through some of the post I realized it’s new to me. Anyhow,
    I’m definitely happy I found it and I’ll be bookmarking and checking back often!

  17. I’m not sure exactly why but this website is loading very slow for me.
    Is anyone else having this problem or is it a problem on my end?
    I’ll check back later and see if the problem still exists.

  18. My coder is trying to persuade me to move to .net from PHP.
    I have always disliked the idea because of the expenses.

    But he’s tryiong none the less. I’ve been using Movable-type
    on a variety of websites for about a year and am anxious about switching to another platform.
    I have heard good things about blogengine.net. Is
    there a way I can transfer all my wordpress content into it?
    Any help would be really appreciated!

  19. I like the valuable info you provide in your articles.
    I’ll bookmark your blog and check again here regularly.
    I’m quite sure I’ll learn a lot of new stuff right
    here! Best of luck for the next!

  20. Do you mind if I quote a couple of your articles as long as
    I provide credit and sources back to your website? My blog site
    is in the exact same niche as yours and my users would definitely benefit from some
    of the information you provide here. Please let me know if this alright
    with you. Cheers!

  21. I am really enjoying the theme/design of your site. Do you ever run into any internet browser
    compatibility issues? A few of my blog audience have complained about my
    website not working correctly in Explorer but looks
    great in Chrome. Do you have any recommendations to help fix this issue?

  22. Greetings! I know this is kinda off topic but I was wondering which blog platform
    are you using for this website? I’m getting sick and
    tired of WordPress because I’ve had issues with hackers and I’m looking at alternatives for
    another platform. I would be awesome if you could point me in the direction of a good platform.

  23. magnificent publish, very informative. I’m wondering
    why the other experts of this sector do not notice this.
    You must proceed your writing. I am sure, you’ve a great readers’ base already!

  24. Magnificent beat ! I would like to apprentice whilst
    you amend your web site, how could i subscribe for a blog website?

    The account helped me a appropriate deal. I have been a little bit acquainted of this your broadcast
    offered brilliant clear concept

  25. Great goods from you, man. I have understand your stuff previous to and you’re just too great.

    I actually like what you’ve acquired here, certainly like
    what you are stating and the way in which you say it.
    You make it entertaining and you still care for to keep it sensible.
    I can’t wait to read far more from you. This is really a wonderful web site.

  26. I think that everything published made a great deal of sense.
    But, what about this? what if you typed a catchier title?

    I mean, I don’t wish to tell you how to run your website, but suppose
    you added a title that makes people want more?
    I mean Send email notification in Laravel 5.6 – Kodementor is kinda plain. You
    could peek at Yahoo’s front page and note how they create news
    headlines to get people to open the links. You might add a related video or a related pic or two
    to grab readers interested about everything’ve got to say.

    Just my opinion, it would bring your posts a little bit more interesting.

  27. I’m not sure exactly why but this weblog is loading incredibly
    slow for me. Is anyone else having this issue or is
    it a problem on my end? I’ll check back later on and
    see if the problem still exists.

  28. Hello there, just became alert to your blog through Google,
    and found that it’s truly informative. I am gonna watch out for brussels.
    I’ll appreciate if you continue this in future. A lot of people will
    be benefited from your writing. Cheers!

  29. Admiring the dedication you put into your site and detailed information you
    provide. It’s great to come across a blog every once in a
    while that isn’t the same outdated rehashed material. Wonderful read!
    I’ve saved your site and I’m adding your RSS feeds to my Google account.

  30. May I simply just say what a relief to uncover
    somebody that truly knows what they are talking about on the net.
    You definitely realize how to bring a problem to light and make it important.

    More people really need to check this out and understand this side of the story.
    I was surprised you are not more popular given that you surely have
    the gift.

  31. Hello there, I found your web site by means of Google whilst looking for a
    related topic, your site got here up, it appears great.
    I have bookmarked it in my google bookmarks.
    Hi there, just turned into aware of your blog through Google, and found that it is really informative.
    I am going to watch out for brussels. I will appreciate if you proceed this in future.
    Numerous other folks might be benefited from your writing.
    Cheers!

  32. Nice post. I was checking constantly this weblog and I’m inspired!
    Extremely helpful info specially the remaining part 🙂 I maintain such info much.
    I used to be looking for this certain info for a long time.
    Thank you and good luck.

  33. I absolutely love your blog.. Excellent colors & theme.
    Did you build this site yourself? Please reply back
    as I’m attempting to create my very own site and would like to
    find out where you got this from or what the theme is named.
    Many thanks!

  34. of course like your website however you need to test the spelling
    on quite a few of your posts. Many of them are rife
    with spelling problems and I to find it very bothersome to inform the reality however I will definitely come
    back again.

  35. Howdy! I could have sworn I’ve been to this site before but after checking through some of the post I realized it’s new to me.

    Anyhow, I’m definitely delighted I found it and I’ll be bookmarking
    and checking back frequently!

  36. Today, I went to the beachfront with my kids.
    I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.”
    She placed the shell to her ear and screamed. There was a hermit crab inside
    and it pinched her ear. She never wants to go back! LoL I know this
    is completely off topic but I had to tell someone!

  37. The very best man is usually the grooms most reliable and faithful good
    friend or relative. The best man is usually the grooms most trustworthy
    and faithful buddy or relative. The ushers may be the grooms brothers, cousin, or best
    friends, or brothers and close kinfolk of the bride.
    Responsibilities of the perfect Man Before the wedding, he – pays for his own attire,
    bought or rented. May give the envelope to the officiant
    before the ceremony. Throughout the ceremony, he –
    is just not a part of the processional however enters with the groom, standing behind the groom and barely to
    the left. After the ceremony, he – immediately serves as one
    of many witnesses in signing the marriage license. At the reception, he
    – doesn’t stand within the receiving line except he is also the father of the groom.
    After the reception, he – promptly returns each his and
    the grooms rented formal wear to the suitable location.

  38. Thank you a bunch for sharing this with all of us you really
    understand what you are speaking approximately!
    Bookmarked. Kindly also talk over with my site =).
    We may have a link trade contract among us

  39. Fantastic goods from you, man. I’ve understand your stuff
    previous to and you are just too fantastic.
    I actually like what you’ve acquired here, certainly like what you’re saying and the way in which
    you say it. You make it enjoyable and you still take
    care of to keep it sensible. I cant wait to read
    far more from you. This is actually a tremendous site.

  40. Hi! I just would like to offer you a huge thumbs up for your excellent info you have here on this post.
    I’ll be returning to your blog for more soon.

  41. First off I want to say awesome blog! I had a
    quick question which I’d like to ask if you don’t mind.
    I was interested to find out how you center yourself and clear your thoughts before writing.
    I have had trouble clearing my thoughts in getting my ideas out.

    I do enjoy writing but it just seems like the first 10 to 15 minutes tend to be lost just trying
    to figure out how to begin. Any suggestions or hints?
    Appreciate it!

  42. I loved as much as you will receive carried out
    right here. The sketch is attractive, your authored subject matter stylish.
    nonetheless, you command get got an impatience over that you wish be delivering the following.
    unwell unquestionably come more formerly again since exactly the same nearly very often inside case you shield this increase.

  43. Hi there! I could have sworn I’ve visited this site before but after looking at a
    few of the posts I realized it’s new to me. Regardless, I’m certainly pleased I found it
    and I’ll be book-marking it and checking back frequently!

  44. I am extremely impressed with your writing skills as well
    as with the layout on your blog. Is this a paid theme or did you modify it yourself?
    Either way keep up the nice quality writing, it’s rare to see a nice
    blog like this one nowadays.

  45. of course like your web site however you have to test the spelling
    on quite a few of your posts. Many of them are rife with spelling issues and I find it very troublesome to
    tell the truth then again I will definitely come back again.

  46. Nice post. I was checking continuously this blog and I am impressed!
    Very helpful info specially the ultimate section :
    ) I maintain such info much. I was seeking this particular information for a very lengthy time.
    Thanks and best of luck.

  47. Wow that was odd. I just wrote an extremely long comment
    but after I clicked submit my comment didn’t show up. Grrrr…

    well I’m not writing all that over again. Anyways, just wanted to say superb blog!

  48. Have you ever thought about creating an ebook or guest authoring on other blogs?
    I have a blog based on the same ideas you discuss and would really like to
    have you share some stories/information. I know my subscribers would
    enjoy your work. If you’re even remotely interested, feel free to send me an e-mail.

  49. Hi there! Do you know if they make any plugins to assist with SEO?
    I’m trying to get my blog to rank for some targeted keywords but I’m not
    seeing very good success. If you know of any please share.
    Thanks!

LEAVE A REPLY

Please enter your comment!
Please enter your name here