Laravel SDK

Setup & Initialization

INFO

Our Laravel Server SDK is compatible with Laravel 9, 10 or 11. If you’re using a different version please use our PHP Server SDK.

  1. Install Package:

To install the Laravel Server SDK you may need to set your composer.json’s "minimum-stability" field to "dev", then:

composer require notificationapi/notificationapi-laravel-server-sdk:@dev

Or, if you prefer to keep your composer.json’s "minimum-stability" field set to "stable", then:

composer require notificationapi/notificationapi-php-server-sdk:@dev
composer require notificationapi/notificationapi-laravel-server-sdk:@dev -W
  1. Register the NotificationApiServiceProvider:

For Laravel 9 or 10 add the service provider to config/app.php.

'providers' => [
	// ...
	NotificationAPI\NotificationApiServiceProvider::class,
]

For Laravel 11 add the service provider to bootstrap/providers.php.

return [
	// ...
	NotificationAPI\NotificationApiServiceProvider::class,
]
  1. Add NotificationAPI keys to .env:
NOTIFICATION_API_KEY=clientID
NOTIFICATION_API_SECRET=clientSecret

No region variable is required for US region, but if using the CA (Canada) region add:

NOTIFICATION_API_REGION=CA

Or, if using the EU (Europe) region add:

NOTIFICATION_API_REGION=EU
  1. Add this class to Models/NotificationUser.php for creating a user:
<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;

class NotificationUser
{
    use Notifiable;

    /**
     * The user's ID.
     *
     * @var string
     */
    public $id;

    /**
     * The user's email address.
     *
     * @var string
     */
    public $email;

    /**
     * The user's phone number.
     *
     * @var string
     */
    public $number;

    /**
     * Create a new notification user instance.
     *
     * @return void
     */
    public function __construct()
    {
        // Empty constructor to allow property assignment
    }

    /**
     * Route notifications for the notification-api channel.
     *
     * @return string
     */
    public function routeNotificationForNotificationApi()
    {
        return $this->id;
    }
}
  1. Generate Notification class:
php artisan make:notification MyNotification
  1. Update the Notification class:
class MyNotification extends Notification
{
    // ...

    protected $parameters;

     /**
     * Create a new notification instance.
     */
    public function __construct($parameters = null)
    {
        $this->parameters = $parameters;
    }

    // Update existing via function
    public function via($notifiable)
    {
        // Add to or replace existing values (e.g. 'mail')
        return ['notification-api'];
    }

    public function toNotificationApi($notifiable)
    {
        return [
            "type" => "my_notification_id",
            "to" => [
                "id" => $notifiable->getAttribute('id'),
                "email" => $notifiable->getAttribute('email'),
            ],
            "parameters" => $this->parameters
        ];
    }
}
NameTypeDescription
clientId*stringYour NotificationAPI account clientId. You can get it from here.
clientSecret*stringYour NotificationAPI account client secret. You can get it from here.
regionstringTo choose a different region than default (US). Use CA to access the Canada region, and EU for the Europe region.

* required

Send

Used to send a notification to the specified user.

Pass content directly without templates

You can ignore the templates and pass the content directly through the API by specifying channel content objects on the request.

$user = new NotificationUser();
$user->id = "spongebob.squarepants";
$user->email = "spongebob@squarepants.com";
$user->number = "+15005550006";

$user->notify(new MyNotification([
    "type" => "order_tracking",
    "email" => [
      "subject" => "Your Krabby Patty Order is Ready!",
      "html" => "<h1>Order Update</h1><p>Your order is ready for pickup!</p>",
      "senderName" => "Krusty Krab",
      "senderEmail" => "orders@krustykrab.com"
    ],
    "sms" => [
      "message" => "Your Krabby Patty order is ready for pickup!"
    ],
    "inapp" => [
      "title" => "Order Update",
      "image" => "https://example.com/image.png",
      "url" => "https://example.com"
    ],
    "web_push" => [
      "title" => "Order Update",
      "message" => "Your Krabby Patty order is ready for pickup!",
      "icon" => "https://example.com/icon.png",
      "url" => "https://example.com"
    ],
    "mobile_push" => [
      "title" => "Order Update",
      "message" => "Your Krabby Patty order is ready for pickup!"
    ],
    "slack" => [
      "text" => "Your Krabby Patty order is ready for pickup!"
    ]
]));

With templates and parameters

Use templates you designed in the Dashboard and inject dynamic values with parameters. The server renders your templates per-channel using the values you provide.

This example will send notifications over the channels and templates specified in our dashboard:

INFO

To learn more about parameters, see Parameters (Merge Tags), and to learn more about templates, see Templating.

The notificationapi-laravel-server-sdk package uses Laravel’s notifications. Add this code to your project to send a notification:

<?php

use App\Models\NotificationUser;
use App\Notifications\MyNotification;

$user = new NotificationUser();
$user->id = "test_user_id";
$user->email = "spongebob@squarepants.com";
$user->number = "+15005550006";


// Optional parameters to customize the notification
$parameters = [
  "item" => "Krabby Patty Burger",
  "address" => "124 Conch Street"
  "commentId" => "1234567890"
];

// Send the notification to the user
$user->notify(new MyNotification($parameters));

// If you don't have parameters, you can simply call:
// $user->notify(new MyNotification());

:::info Alternatively you can send a notification without using Laravel’s notifications: :::

$data = [
  "type" => "my_notification_id",
  "to" => [
    "id" => "test_user_id",
    "email" => "spongebob@squarepants.com",
    "number" => "+15005550006"
  ],
  "parameters" => [
    "item" => "Krabby Patty Burger",
    "address" => "124 Conch Street",
    "commentId" => "1234567890"
  ]
];

$result = notification_api($data);
#or
$result = (new NotificationApiService)->send($data)

Parameters

The send() method accepts an object with the following fields:

NameTypeDescription
type*stringThe ID of the notification you wish to send. You can find this value from the dashboard.
to*objectThe user to send the notification to.
to.id*stringThe ID of the user in your system. Required. This is the only user field required for sending in-app, web push, and mobile push notifications.
to.emailstringRequired for sending email notifications, otherwise optional.
to.numberstringRequired for SMS/CALL notifications, otherwise optional. Valid format: +15005550006. Unformatted US/Canada numbers are also accepted, e.g., (415) 555-1212, 415-555-1212, or 4155551212.
to.timezonestringThe user’s timezone. Timezone names correspond to the Zone and Link names of the IANA Time Zone Database, such as β€˜America/New_York’, β€˜America/Denver’, β€˜EST’, and β€˜UTC’.
parametersobjectUsed to pass in dynamic values into the notification design. Read more: Dynamic Parameters (Merge Tags)
schedulestringAn ISO 8601 datetime string to schedule the notification for. For example, 2024-02-20T14:38:03.509Z. Read more: Scheduling
replaceobject, string key/value pairSimilar to parameters, but more flexible. Like the programmatic string replace function, this parameter will replace any string in the notification templates with another string. This operation happens on the fly when sending the notification and does not actually modify the templates.
This operation is case-sensitive and happens after parameters are injected.
subNotificationIdstringTo break down your notification into multiple categories or groups. Read more: Sub Notifications
templateIdstringBy default, notifications are sent using the default template of each channel. You can permanently change the default template from the dashboard. However, you can also use this parameter to force using a specific template. This is useful in multiple situations:
- Design variation: using different wording and design, e.g. β€œYou have new updates” vs. β€œYou don’t have any updates”
- White-labeling: using a specific template that you designed for a white-labeled customer
- Language: creating and using multiple templates for multiple languages
If the provided templateId does not exist for a channel, the default template will be used, and a warning message will be generated.
forceChannels (deprecated)string[]Used to override the channels which are used for the notification. This field only overrides the notification’s channels configuration. It does not override the user preferences.
Values available for use are:
EMAIL, INAPP_WEB, SMS, CALL, PUSH, WEB_PUSH
E.g. forceChannels: ["EMAIL", "SMS"]
optionsobjectFor configuring additional options
emailobjectOverride the email template by providing the complete email content. When provided, this will replace the dashboard template for the email channel.
email.subject*stringThe email subject line. Required when using email override.
email.html*stringThe HTML content of the email. Required when using email override.
email.previewTextstringThe email preview text that appears in email clients.
email.senderNamestringThe sender name for the email.
email.senderEmailstringThe sender email address.
smsobjectOverride the SMS template by providing the complete SMS content. When provided, this will replace the dashboard template for the SMS channel.
sms.message*stringThe SMS message content. Required when using SMS override.
sms.autoReplyobjectConfigure automatic reply to inbound SMS messages. See Inbound Messages for details.
sms.autoReply.message*stringThe auto-reply message to send when a recipient replies to your SMS. Sent once per recipient phone number per account. Opt-out keywords (STOP, CANCEL, etc.) skip auto-reply.
inappobjectOverride the in-app notification template by providing the complete in-app content. When provided, this will replace the dashboard template for the in-app channel.
inapp.title*stringThe in-app notification title. Required when using in-app override.
inapp.urlstringThe URL to navigate to when the in-app notification is clicked.
inapp.imagestringThe image URL for the in-app notification.
callobjectOverride the call notification template by providing the complete call content. When provided, this will replace the dashboard template for the call channel.
call.message*stringThe call message content. Required when using call override.
web_pushobjectOverride the web push notification template by providing the complete web push content. When provided, this will replace the dashboard template for the web push channel.
web_push.title*stringThe web push notification title. Required when using web push override.
web_push.message*stringThe web push notification message. Required when using web push override.
web_push.iconstringThe icon URL for the web push notification.
web_push.urlstringThe URL to navigate to when the web push notification is clicked.
mobile_pushobjectOverride the mobile push notification template by providing the complete mobile push content. When provided, this will replace the dashboard template for the mobile push channel.
mobile_push.title*stringThe mobile push notification title. Required when using mobile push override.
mobile_push.message*stringThe mobile push notification message. Required when using mobile push override.
slackobjectOverride the Slack notification template by providing the complete Slack content. When provided, this will replace the dashboard template for the Slack channel.
slack.text*stringThe Slack message text. Required when using Slack override.
slack.blocksobject[]Slack Block Kit blocks for rich formatting. Optional when using Slack override.

Options Object

NameTypeDescription
emailobjectEmail options features.
email.replyToAddressesstring[]

An array of email addresses that will receive responses when recipients reply to the notification email. This enables two-way email communication, allowing recipients to respond directly to notifications.

email.ccAddressesstring[]An array of emails to be CC’ed on the email notifications.
email.bccAddressesstring[]An array of emails to be BCC’ed on the email notifications.
email.fromNamestringA string to display as the β€œFrom” field in an email.
email.fromAddressstring

An email address to send the email from. To use a custom email.fromAddress from your domain, you must verify your domain in your NotificationAPI dashboard. Read more: Domain Verification

email.attachments

Array<{ filename: string; url: string } | { filename: string; content: string; contentType?: string }>

An array of attachments. Each attachment must be either URL-based OR base64 content-based (mutually exclusive). The API validates this using a oneOf schema. The URLs only need to be valid for a few minutes after calling the SDK method and can be invalidated afterwards for privacy. The maximum email size (including the content and all attachments) is 25MB. Provide file extensions in filename for better UX on recipient devices.

apnobjectAdditional Apple push notification options.
apn.expirynumber

The UNIX timestamp representing when the notification should expire. This does not contribute to the 2048 byte payload size limit. An expiry of 0 indicates that the notification expires immediately.

apn.prioritynumber

The priority of the notification. If you omit this header, APNs sets the notification priority to 10. Specify 10 to send the notification immediately. Specify 5 to send the notification based on power considerations on the user’s device. Specify 1 to prioritize the device’s power considerations over all other factors for delivery, and prevent awakening the device.

apn.collapseIdstring

An identifier you use to merge multiple notifications into a single notification for the user. Typically, each notification request displays a new notification on the user’s device. When sending the same notification more than once, use the same value in this header to merge the requests. The value of this key must not exceed 64 bytes.

apn.threadIdstring

Provide this key with a string value that represents the app-specific identifier for grouping notifications. If you provide a Notification Content app extension, you can use this value to group your notifications together. For local notifications, this key corresponds to the threadIdentifier property of the UNNotificationContent object.

apn.badgenumber

Include this key when you want the system to modify the badge of your app icon. If this key is not included in the dictionary, the badge is not changed. To remove the badge, set the value of this key to 0.

apn.soundstring

Include this key when you want the system to play a sound. The value of this key is the name of a sound file in your app’s main bundle or in the Library/Sounds folder of your app’s data container. If the sound file cannot be found, or if you specify default for the value, the system plays the default alert sound. For details about providing sound files for notifications; see

here

.

apn.contentAvailableboolean

Include this key with a value of 1 to configure a background update notification. When this key is present, the system wakes up your app in the background and delivers the notification to its app delegate. For information about configuring and handling background update notifications, see

here

.

fcmobjectAdditional Firebase Cloud Messaging push notification options.
fcm.androidobjectAdditional Android push notification options.
fcm.android.collapseKeystring

This parameter identifies a group of messages (e.g., with collapse_key: β€œUpdates Available”) that can be collapsed, so that only the last message gets sent when delivery can be resumed. This is intended to avoid sending too many of the same messages when the device comes back online or becomes active. Note that there is no guarantee of the order in which messages get sent. Note: A maximum of 4 different collapse keys is allowed at any given time. This means a FCM connection server can simultaneously store 4 different send-to-sync messages per client app. If you exceed this number, there is no guarantee which 4 collapse keys the FCM connection server will keep.

fcm.android.prioritystring

Sets the priority of the message. Valid values are normal and high. On iOS, these correspond to APNs priorities 5 and 10. By default, notification messages are sent with high priority, and data messages are sent with normal priority. Normal priority optimizes the client app’s battery consumption and should be used unless immediate delivery is required. For messages with normal priority, the app may receive the message with unspecified delay. When a message is sent with high priority, it is sent immediately, and the app can wake a sleeping device and open a network connection to your server.

fcm.android.ttlstring

This parameter specifies how long (in seconds) the message should be kept in FCM storage if the device is offline. The maximum time to live supported is 4 weeks, and the default value is 4 weeks. For more information, see

Setting the lifespan of a message

.

INFO

To use a custom fromAddress from your domain, you’ll need to verify your domain first. See your NotificationAPI dashboard for Domain Verification setup instructions. We strongly recommend you to verify your domain before sending emails from production.

Size Limitation

When using parameters (merge tags) in the body of your notifications, it is recommended that the size of the combined parameters not exceed 150 KB. Exceeding this limit may result in delivery failure, or an API error.