How to Create & Send Email Notification in Laravel 9

This quick and simple Laravel Notification example tutorial will help you learn how to send an email notification in Laravel.

A notification mail or triggered email is sent to users to persuade about something. By sending a mail to the user, you grab their attention so that they don’t forget something essential.

You will generate a notifications table through the artisan mechanism, bind some information, and send the notification in laravel. Moreover, you will be creating a Laravel email notification tutorial from starting.

Laravel 9 Email Notification Example

Throughout this tutorial, we will share step-by-step methods that will help you learn to create an app from scratch.

Making a connection with the database, creating a notification table, migration, creating controller, creating and binding routes to a controller not only but also how to send an email notification with example.

Create Laravel App

If not created yet, create a new laravel project:

composer create-project laravel/laravel laravel-email-notification --prefer-dist

Add Database Info in ENV

Adding database information for example database name, username and password in .env config file establish the connection among Laravel and Database:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db
DB_USERNAME=root
DB_PASSWORD=

Generate Notification Migration

You have to create notification migration file with given below command:

php artisan notifications:table

Here is your notification file generated at the following pathmigrations/create_notifications_table.php:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateNotificationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('notifications', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->string('type');
            $table->morphs('notifiable');
            $table->text('data');
            $table->timestamp('read_at')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('notifications');
    }
}

Run the migration:

php artisan migrate

You can check the notification table in PHPMyAdmin, and it will allow you to send email notification and store into the database.

Create Notification Class

The php artisan make:notification command will create a Billing notification class:

php artisan make:notification BillingNotification

Add your code in app/Notifications/BillingNotification.php file:

<?php

namespace App\Notifications;

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

class BillingNotification extends Notification
{
    use Queueable;
    private $billData;

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

    /**
     * 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)                    
            ->name($this->billData['name'])
            ->line($this->billData['body'])
            ->action($this->billData['text'], $this->billData['url'])
            ->line($this->billData['thanks']);
    }

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

Create Controller

Generate a new controller to manage the notification code:

php artisan make:controller BillController

Put the given code in app/Http/Controllers/BillController.php.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Notification;
use App\Models\User;
use App\Notifications\BillingNotification;

class BillController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
  
    public function index()
    {
        return view('welcome');
    }
    
    public function sendNotification() {

        $data = User::first();
  
        $billData = [
            'name' => '#007 Bill',
            'body' => 'You have received a new bill.',
            'thanks' => 'Thank you',
            'text' => '$600',
            'offer' => url('/'),
            'bill_id' => 30061
        ];
  
        Notification::send($data, new BillingNotification($billData));
   
        dd('Bill notification has been sent!');
    }
}

Create Route

Place the code in routes/web.php:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BillController;

/*
|--------------------------------------------------------------------------
| 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('/', [BillController::class, 'sendNotification']);

Send Email Notification in Laravel 9

Open console, start the application:

php artisan serve

Here is the URL that will send the email notification:

http://127.0.0.1:8000

Finally, this Laravel Notification tutorial is done, you have seen the example to send email notification in Laravel application.