Laravel 11 Send Email Via Notification Example

By Hardik Savani September 4, 2024 Category : Laravel

In this article, we will learn how to create and send mail notifications in the laravel 11 application.

Laravel notifications are a powerful feature of the Laravel PHP framework that allows you to send notifications to your users. we will send email via notification in laravel 11 application.

Notifications in Laravel are implemented using a notification class that extends the Illuminate\Notifications\Notification class. Within the notification class, you can define the content and format of the notification, as well as the channel or channels that the notification should be sent through.

Laravel provides a variety of built-in channels that you can use to send notifications, such as mail for sending email notifications, database for storing notifications in a database, and broadcast for broadcasting notifications over web sockets. You can also create custom channels for sending notifications through other mediums.

In this example, we will create a simple BirthdayWish notification using a notification. We will send it to the user on their birthday. So, let's follow the following steps to complete this simple example.

Step for Laravel 11 Send Email Via Notification Example

  • Step 1: Install Laravel 11
  • Step 2: Create Migration
  • Step 3: Update Model
  • Step 4: Create Notification
  • Step 5: Create Route
  • Step 6: Create Controller
  • Run Laravel App

Step 1: Install Laravel 11

This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Create Migration

Here, we will create a new migration to add a new column birthdate to the users table. So let's run the following command:

php artisan make:migration add_birthdate_column

After this command, you will find one file in the following path: "database/migrations". You have to put the below code in your migration file to create the products table.

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->date('birthdate')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        
    }
};

Now you have to run this migration by the following command:

php artisan migrate

Step 3: Update Model

In this step, we will add "birthdate" column in $fillable array.

Make sure you use Notifiable class form Illuminate\Notifications\Notifiable.

let's copy below code and paste it.

app/Models/User.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'birthdate'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }
}

Step 4: Create Notification

In this step, we need to create "Notification" by using the Laravel artisan command, so let's run the command below. We will create the BirthdayWish notification class.

php artisan make:notification BirthdayWish

Now you can see a new folder created as "Notifications" in the app folder. You need to make the following changes as shown in the class below.

app/Notifications/BirthdayWish.php

<?php
  
namespace App\Notifications;
  
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
  
class BirthdayWish extends Notification
{
    use Queueable;
  
    private $messages;
  
    /**
     * Create a new notification instance.
     */
    public function __construct($messages)
    {
        $this->messages = $messages;
    }
  
    /**
     * Get the notification's delivery channels.
     *
     * @return array
     */
    public function via(object $notifiable): array
    {
        return ['mail'];
    }
  
    /**
     * Get the mail representation of the notification.
     */
    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage)
                    ->line($this->messages['hi'])
                    ->line($this->messages['wish'])
                    ->line('Thank you for using our application!');
    }
  
    /**
     * Get the array representation of the notification.
     *
     * @return array
     */
    public function toArray(object $notifiable): array
    {
        return [
              
        ];
    }
}

Next, you have to add the send mail configuration with mail driver, mail host, mail port, mail username, and mail password so Laravel will use those sender configurations for sending email. You can simply add it as follows:

.env

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=mygoogle@gmail.com
MAIL_PASSWORD=rrnnucvnqlbsl
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=mygoogle@gmail.com
MAIL_FROM_NAME="${APP_NAME}"

Step 5: Create Route

In this step, we need to create routes for sending notifications to one user. So open your "routes/web.php" file and add the following route.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\UserController;
    
Route::get('user-notify', [UserController::class, 'index']);

Step 6: Create Controller

Here, we require the creation of a new controller, UserController, with an index method to send a notification route. So let's put the code below.

app/Http/Controllers/UserController.php

<?php
   
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use App\Models\User;
use App\Notifications\BirthdayWish;
    
class UserController extends Controller
{   
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $user = User::find(1);
  
        $messages["hi"] = "Hey, Happy Birthday {$user->name}";
        $messages["wish"] = "On behalf of the entire company I wish you a very happy birthday and send you my best wishes for much happiness in your life.";
          
        $user->notify(new BirthdayWish($messages));
  
        dd('Done');
    }
}

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/user-notify

Output: You Email Look Like This

I hope it can help you...

Shares