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:
- Return
SendGridChannel::classin thevia()method. (Notmail) - 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.