DEV Community

Cover image for Laravel 8 Email Notification Example
Code And Deploy
Code And Deploy

Posted on

Laravel 8 Email Notification Example

Originally posted @ https://codeanddeploy.com visit and download the sample code:
https://codeanddeploy.com/blog/laravel/laravel-8-email-notification-example

In this post, I will show you an example how to implement Laravel 8 email notifications. We know that email notifications is one of the most important functionality to implement in our web application as well as in Laravel framework. Laravel provide an easy way of sending email using Notification class that easily send to any delivery channels such as email, SMS, and Slack. The advantage of using Notification on Laravel is that this is already associated with the specified user we just put a parameter of User object value then the class will handle the sending.

In Laravel notification we can also save it to our database so that easily display in our web interface.

In this Laravel notification example we are using email to notify the User with the project assigned.

Kindly follow the following below to learn about Laravel email notification.

Step 1: Laravel Installation

If you don't have a Laravel 8 install in your local just run the following command below:

composer create-project --prefer-dist laravel/laravel laravel-email-notification
Enter fullscreen mode Exit fullscreen mode

Step 2: Database Configuration

If your Laravel project is fresh then you need to update your database credentials. Just open the .env file in your Laravel 8 project.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name_here
DB_USERNAME=your_database_username_here
DB_PASSWORD=your_database_password_here
Enter fullscreen mode Exit fullscreen mode

Step 3: Migration Setup

Here we need to generate first the notifications table before running the migrations. Kindly run the following command:

php artisan notifications:table
Enter fullscreen mode Exit fullscreen mode
php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Then once done let's create a seeder for our user. Run the following command:

php artisan make:seeder CreateUsersSeeder
Enter fullscreen mode Exit fullscreen mode

Once our seeder is generated kindly to the database/seeders directory. Open the CreateUsersSeeder.php and you will see the following code:

<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Seeder;

class CreateUsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        User::create([
            'name' => 'Juan',
            'email' => 'email@gmail.com',
            'password' => bcrypt('password')
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Then run the following command:

php artisan db:seed --class=CreateUsersSeeder
Enter fullscreen mode Exit fullscreen mode

Learn more about Laravel seeder here.

Step 4: Making Laravel Email Notification

Now, let's generate our Laravel email notification example we will name this as EmailNotification. Run the following command to do this.

php artisan make:notification EmailNotification
Enter fullscreen mode Exit fullscreen mode

Once done, navigate App/Notifications and open EmailNotification.php then edit it. See below example:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class EmailNotification extends Notification
{
    use Queueable;

    /**
     * @var array $project
     */
    protected $project;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($project)
    {
        $this->project = $project;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail','database'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->greeting($this->project['greeting'])
                    ->line($this->project['body'])
                    ->action($this->project['actionText'], $this->project['actionURL'])
                    ->line($this->project['thanks']);
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toDatabase($notifiable)
    {
        return [
            'project_id' => $this->project['id']
        ];
    }

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

Step 4: Setting up Routes

In my example, I will create manually my crud routes. Just open the "routes/web.php" file and add the following routes.

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| 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('/', function () {
    return view('welcome');
});

Route::get('/send', '\App\Http\Controllers\HomeController@send')->name('home.send');
Enter fullscreen mode Exit fullscreen mode

Step 5: Setting Up Controller

In this section we will add our email notification in our HomeController as we set in our routes. See below complete code of our controller:

<?php

namespace App\Http\Controllers;

use Notification;
use App\Models\User;
use Illuminate\Http\Request;
use App\Notifications\EmailNotification;

class HomeController extends Controller
{
    public function send() 
    {
        $user = User::first();

        $project = [
            'greeting' => 'Hi '.$user->name.',',
            'body' => 'This is the project assigned to you.',
            'thanks' => 'Thank you this is from codeanddeploy.com',
            'actionText' => 'View Project',
            'actionURL' => url('/'),
            'id' => 57
        ];

        Notification::send($user, new EmailNotification($project));

        dd('Notification sent!');
    }
}
Enter fullscreen mode Exit fullscreen mode

Now our code is ready for sending notification to our user. You can test it now by running the serve command:

php artisan serve
Enter fullscreen mode Exit fullscreen mode

Then run the url below to your browser to send email notification to your user.

http://127.0.0.1:8000/send
Enter fullscreen mode Exit fullscreen mode

Now Laravel sent email notification. See below output:

laravel-8-email

Laravel also provide a way of sending option.

$user->notify(new EmailNotification($project));

Enter fullscreen mode Exit fullscreen mode

And you can get the user notifications by using the following code.

dd($user->notifications);
Enter fullscreen mode Exit fullscreen mode

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/laravel-8-email-notification-example if you want to download this code.

Happy coding :)

Top comments (0)