Send email notification in Laravel 5.6

831
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://www.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.

43 COMMENTS

  1. Have you ever thought about adding a little bit more than just your articles?
    I mean, what you say is valuable and everything. But imagine
    if you added some great pictures or video clips to give
    your posts more, “pop”! Your content is excellent
    but with pics and videos, this blog could undeniably be one of the most
    beneficial in its field. Excellent blog!

    Also visit my webpage :: 도도 그래프 사이트 (http://www.mt-jobs.net)

  2. It’s no wonder, either-Boston has a lot to supply like a city that it’s almost incredible that men and women don’t apready think it over the uncontested besst position to reside in the US.
    These investments could include certificate off deposits and certificate of investments in addition. The localities where Bangalore
    real estate property hhas seen a depreciation in psf rates of rental residences are HSR Layout, R.

    Stop by my webpage … anchortext (Phil)

  3. WM casino is typically the best live casino game provider site
    in Asia. As a possible official live casino betting site,
    we are usually willing to provide typically the game with the
    best features to ensure all online betting fans inside Asia.
    All online games that we supply are online in addition to an easy task to understand.
    Upon our site, you will also get the best services from our dealers who
    are all set to last twenty-four hours. You likewise does
    not have to worry regarding your payment in addition to data because we
    have obtained established permission to marketplace our products formally
    to Indonesia.

    Exactly how to Register WM Casino
    For possible members who wish to sign up WM
    casino can directly visit our agent to checklist WM casino because we have given official permission to promote our products all through Asia with typically the standards
    that we all have set. Which means you as a wagering fan in Indonesia can make WM on line casino
    agents without getting to worry. The right way to register
    at WM casino agent may be really easy, simply by completing data such
    as account name, accounts number, valid phone number and some questions for member
    accounts security. Our team provides the same account registration specifications for all our agents to ensure the security of
    member data will be taken care of so well.

  4. Link exchange is nothing else however it is just placing the other person’s webpage link
    on your page at appropriate place and other person will also do same
    in favor of you.

  5. We are a group of volunteers and starting a new scheme in our community.
    Your web site provided us with valuable info to work on. You have
    done an impressive job and our whole community will
    be thankful to you.

  6. Hello, this weekend is fastidious designed for me, since this point
    in time i am reading this enormous informative paragraph here at my residence.

  7. Thank you for the auspicious writeup. It in reality used to be a amusement account it.
    Glance advanced to more added agreeable from you!
    However, how can we communicate?

  8. Your mode of describing the whole thing in this piece of writing is in fact nice, all be capable
    of effortlessly know it, Thanks a lot.

    Here is my web page; jasa social media management;
    Ayuokta.Home.blog,

  9. certainly like your web-site however you have to test the spelling on several of your posts.
    A number of them are rife with spelling issues and I find it very troublesome to inform the reality nevertheless
    I will surely come back again.

  10. Oh my goodness! Incredible article dude! Many thanks, However I am going
    through problems with your RSS. I don’t understand
    the reason why I can’t subscribe to it. Is there anybody else having similar RSS issues?
    Anyone that knows the solution can you kindly respond?
    Thanks!!

  11. Do you mind if I quote a couple of your posts as long
    as I provide credit and sources back to your site?

    My blog is in the very same niche as yours and my visitors
    would truly benefit from a lot of the information you present
    here. Please let me know if this alright with you. Many
    thanks!

  12. Wow, awesome blog format! How long have you been running a
    blog for? you make running a blog look easy. The full look of your web site
    is wonderful, let alone the content!

  13. Hey! Do you know if they make any plugins to protect against hackers?
    I’m kinda paranoid about losing everything I’ve worked hard on.
    Any suggestions?

  14. Helpful info. Fortunate me I found your website accidentally, and I am surprised why this twist of fate did not
    happened earlier! I bookmarked it.

  15. wonderful issues altogether, you simply won a brand new reader.
    What could you recommend in regards to your put up
    that you made a few days in the past? Any positive?

  16. I like the helpful information you provide in your articles.
    I will bookmark your weblog and check again here regularly.
    I am quite certain I’ll learn plenty of new stuff right here!
    Best of luck for the next!

  17. Career Opportunity:

    – Waitress (Thai Speciality Cuisine)
    – Bar Waitress
    – F&B Coordinator

    Looking for enthusiastic and creative team player to become part of the CocoCollection family with minimum 1 year of experiences.

    careergrowth CocoPalm

  18. It is really a great and useful piece of information. I am satisfied that you simply shared this useful info with us.
    Please keep us informed like this. Thanks for sharing.

  19. Valuable info. Lucky me I discovered your website by accident, and I am
    shocked why this twist of fate did not took
    place earlier! I bookmarked it.

  20. Hi, this weekend is pleasant in favor of me, for the reason that this moment i am reading this impressive educational piece of writing here at my residence.

    Feel free to visit my webpage: 먹튀폴리스

  21. Its not my first time to go to see this site, i am visiting this website dailly and take good facts from here every day.

    Feel free to visit my web page clash of clans hack

  22. Hurrah! At last I got a blog from where I know how to actually obtain useful facts regarding my study and knowledge.

    Look at my blog :: free fire free diamonds

  23. Just wish to say your article is as surprising.
    The clearness in your post is simply great and i could assume you
    are an expert on this subject. Well with your permission allow me to grab your RSS feed to keep up to date with forthcoming post.
    Thanks a million and please keep up the enjoyable work.

    Here is my blog post :: gta 5 free money generator

  24. I all the time used to study article in news papers but now as I am
    a user of web so from now I am using net for articles, thanks to web.

  25. Great website you have here but I was wanting to know if
    you knew of any message boards that cover the same topics
    discussed here? I’d really love to be a part of online community where
    I can get opinions from other knowledgeable individuals that share the
    same interest. If you have any recommendations, please let me know.
    Cheers!

  26. Fascinating blog! Is your theme custom made or did you download it from
    somewhere? A design like yours with a few simple tweeks would really make my blog jump out.
    Please let me know where you got your theme.
    Kudos

  27. These are actually fantastic ideas in about blogging.

    You have ttouched some fastidious points here. Any way keep up wrinting.

    Also visit my web site: Service AC Panggilan

  28. Appreciating the persistence you put into your site and in depth information you offer.
    It’s awesome to come across a blog every once in a while
    that isn’t the same unwanted rehashed information. Fantastic read!
    I’ve bookmarked your site and I’m adding your RSS feeds to my Google account.

  29. A fascinating discussion is worth comment. I do believe that you should write more about this topic, it might not be a taboo subject but usually people don’t talk about these subjects.

    To the next! Best wishes!!

  30. Very good post! We will be linking to this particularly great post on our website.
    Keep up the great writing.

  31. This is really fascinating, You’re a very skilled blogger.
    I have joined your rss feed and stay up for in quest of more
    of your excellent post. Additionally, I have shared your web site in my social networks

    Here is my web blog 먹튀폴리스; https://www.먹튀폴리스24.com/,

  32. Good information. Lucky me I discovered your blog
    by chance (stumbleupon). I have bookmarked it for later!

    my page; pubg free uc generator

  33. ⌚1:21 – Introduction of Avenue South Residence⌚3:25 – 1 Bedroom Floor
    Plan Analysis & Review ⌚4:11 – 2 Bedroom Floor Plan Analysis & Review
    ⌚6:03 – 3 Bedroom Floor Plan Analysis & Review⌚6:54 –
    4 Bedroom Floor Plan Analysis & Review⌚7:38 – Editor’s Best Choice of Floor
    Plan⌚8:32 – The Future of Avenue South Residence⌚9:
    55 – Editor’s Review & RecommendNote: Error at ⌚4:36 BP1 is 689sqft instead of 657sqft

  34. Very good blog! Do you have any recommendations for aspiring
    writers? I’m planning to start my own site soon but I’m a little lost on everything.
    Would you suggest starting with a free platform like WordPress
    or go for a paid option? There are so many options out there that I’m
    completely confused .. Any ideas? Thank you!

LEAVE A REPLY

Please enter your comment!
Please enter your name here