Easily Send Laravel Notifications Using Laravel SendGrid

Easily Send Laravel Notifications Using Laravel SendGrid cover image

Laravel Sendgrid Notification Channel allows you to send Laravel notifications using Sendgrid’s Dynamic Transactional Templates feature. Supports Laravel 7.x, 8.x and 9.x.

Installation

To get started, you need to require this package:

composer require swiftmade/laravel-sendgrid-notification-channel

The service provider will be auto-detected by Laravel. If you’ve turned auto-discovery off, add the following service provider in your config/app.php.

NotificationChannels\SendGrid\SendGridServiceProvider::class,

Next, make sure you have a valid Sendgrid API key in config/services.php. You may copy the example configuration below to get started:

return [

    // other services...

    // add this...
    'sendgrid' => [
        'api_key' => env('SENDGRID_API_KEY'),
    ],
];

Usage

To send an email using dynamic templates, you need to:

  1. Return SendGridChannel::class in the via() method. (Not mail)
  2. Add and implement the toSendGrid($notifiable){ } method.

Example:

<?php

namespace App\Notifications;

use Illuminate\Notifications\Notification;
use NotificationChannels\SendGrid\SendGridChannel;

class ExampleNotification extends Notification
{
    public function via($notifiable)
    {
        return [
            SendGridChannel::class,
            // And any other channels you want can go here...
        ];
    }

    // ...

    public function toSendGrid($notifiable)
    {
        return (new SendGridMessage('Your SendGrid template ID'))
            /**
             * optionally set the from address.
             * by default this comes from config/mail.from
             * ->from('no-reply@test.com', 'App name')
             */
            /**
             * optionally set the recipient.
             * by default it's $notifiable->email:
             * ->to('hello@example.com', 'Mr. Smith')
             */
            ->payload([
                "template_var_1" => "template_value_1"
            ]);
	}
}

toSendGrid method will receive a notifiable entity and should return a NotificationChannels\SendGrid\SendGridMessage instance. Unless you set it explicitly, the From address will be set to config('mail.from.address') and the To value will be what returns from notifiable->routeNotificationFor(‘mail’);

For more details, you can visit its complete documentation & source code on Github.

Written by

Rizwan Aslam

Founder and CEO of CodeBrisk, with years of experience building web applications with Laravel and leading a team of expert developers.

More about Rizwan
Book a free call
Book a call with CodeBrisk