Blog Detail

21

Apr
Easily Send Laravel Notifications Using Laravel SendGrid cover image

arrow_back Easily Send Laravel Notifications Using Laravel SendGrid

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.

Published at : 21-04-2022

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project