category: How toApr 09, 2024

The Ultimate Guide to Laravel Reverb: Real-Time Notifications

You learned a lot about using Laravel Reverb in the first part of this guide. Now, you’ll learn how to add real-time notifications seamlessly to your Laravel apps.

You learned a lot about using Laravel Reverb in the first part of this guide. Now, you’ll learn how to add real-time notifications seamlessly to your Laravel apps.

If you’ve used Laravel Nova, you’re likely familiar with the Notification Center. But what if you didn’t need to build one from scratch? Imagine being able to add a real-time notification center to your app in less than five minutes.

If you’re eager to explore the code immediately, you can view the completed code on GitHub. Let’s dive in!

Introducing Novu

Novu is a notification infrastructure tool, built for engineering teams to help them build and set up rich product notification experiences.

Novu provides embeddable Notification Center components, APIs, SDKs and more to help you manage product communication across multiple channels. It provides a full notification infrastructure that provides robust analytics, digest, notification center components, multi-channel notifications and hundreds of notification providers.

Set up Novu

The first step is to sign up on Novu.

Now, run the following command to install the Novu Laravel SDK:

1composer require novu/novu-laravel

Publish the configuration file using this command:

1php artisan vendor:publish --tag="novu-laravel-config"

A configuration file named novu.php with some sensible defaults will be placed in your config directory. Open up your .env file and add the NOVU_API_KEY variable to it.

Note: Grab your API key from Settings in your Novu dashboard.

Before we can start sending and receiving notifications in our app, we need to set up a few things:

  1. Create a Novu workflow for sending notifications,
  2. Create a subscriber – recipient of notifications,
  3. Add a Novu Notification Center component inside our view to display real-time notifications.

Create a Novu Workflow

A workflow is a blueprint for notifications. It includes the following:

  • Workflow name and Identifier
  • Channels: – Email, SMS, Chat, In-App and Push.
  • Channel Notification Content Editor

Follow the steps below to create a workflow:

  1. Click Workflow on the left sidebar of your Novu dashboard.
  2. Click the Add a Workflow button on the top left. You can select a Blank workflow or use one of the existing templates.
  3. The name of the new workflow is currently “Untitled”. Rename it to Laravel In-App Notifications
  4. Select In-App as the channel you want to add.

5. Click on the recently added “In-App” channel and add the following text to it. Once you’re done, click “Update” to save your configuration.

The {{deliveryStatus }}, and {{deliveryHandler}} are custom variables. This means that we can pass them to our payload before we trigger a notification.

You’ll see this when we add the code to trigger a notification.

Create a subscriber

If you click “Subscriber” on the left sidebar of the Novu dashboard, you’ll see the subscriber list. As a first time Novu user, it will be an empty list. Subscribers are your app users.

This implies that when a user registers an account in our app, we must also add them as a subscriber in Novu.

For a test run, open your terminal and run the following script to create a subscriber:

1curl --location '<https://api.novu.co/v1/subscribers>' \\
2  --header 'Content-Type: application/json' \\
3  --header 'Accept: application/json' \\
4  --header 'Authorization: ApiKey <NOVU_API_KEY>' \\
5  --data-raw '{
6    "firstName": "John",
7    "lastName": "Doe",
8    "email": "johndoe@domain.com",
9    "phone": "+1234567890"
10    }'


Note: You can use the details of the user that is already signed up on the app. Refresh the Subscribers page on your Novu dashboard. You should see the recently added subscriber. The one you added via the terminal!

The optimal approach is to add a subscriber through backend code. Just as the user is being added to the database, invoke the code to add the user as a subscriber on Novu. Let’s do that in our app.

We utilized the Laravel JetStream kit. Therefore, our authentication and login logic should be located within the app/Actions/Fortify directory.

Open up app/Actions/Fortify/CreateNewUser.php and modify the class to include Novu logic to create a subscriber on Novu from the user’s details.

1<?php
2
3namespace App\\Actions\\Fortify;
4
5use App\\Models\\User;
6use Illuminate\\Support\\Facades\\Hash;
7use Illuminate\\Support\\Facades\\Validator;
8use Laravel\\Fortify\\Contracts\\CreatesNewUsers;
9use Laravel\\Jetstream\\Jetstream;
10
11class CreateNewUser implements CreatesNewUsers
12{
13    use PasswordValidationRules;
14
15    /**
16     * Validate and create a newly registered user.
17     *
18     * @param  array<string, string>  $input
19     */
20    public function create(array $input): User
21    {
22        Validator::make($input, [
23            'name' => ['required', 'string', 'max:255'],
24            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
25            'password' => $this->passwordRules(),
26            'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['accepted', 'required'] : '',
27        ])->validate();
28
29        $user = User::create([
30            'name' => $input['name'],
31            'email' => $input['email'],
32            'password' => Hash::make($input['password']),
33        ]);
34
35        // Create subscriber on Novu
36        novu()->createSubscriber([
37            'subscriberId' => $user->id,
38            'email' => $user->email,
39            'firstName' => $user->name,
40        ])->toArray();
41
42        return $user;
43    }
44}

Reload your app, create a brand new user and check the Novu subscribers section of your dashboard.

Set up and display Novu Notification Center in your Laravel app

Head over to resources/views/components directory.

Create a notification-center.blade.php file in the directory and add the following code to it:

1<notification-center-component
2      style="{{ $style ?? '' }}"
3      application-identifier="{!! $appId ?? '' !!}"
4      subscriber-id="{!! $subscriberId ?? '' !!}"
5    ></notification-center-component>
6
7<script type="text/javascript">
8    let nc = document.getElementsByTagName('notification-center-component')[0];
9    nc.onLoad = () => console.log('notification center loaded!');
10</script>

Head over to resources/views/layouts/app.blade.php file. At the scripts section, add the following to invoke the Novu Notification Center component:

1<script src="<https://novu-web-component.netlify.app/index.js>" type="text/javascript" defer></script>

In the body, call the notification center blade component like so:

1...
2<div class="min-h-screen bg-gray-100 dark:bg-gray-900">
3            @livewire('navigation-menu')
4
5            <!-- Page Heading -->
6            @if (isset($header))
7
8                
9            <header class="bg-white dark:bg-gray-800 shadow">
10                    <div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
11                        {{ $header }}  
12                    </div>
13                    <div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
14                        <x-notification-center app-id="MavBpIkktq7-" 
15                                    subscriber-id="{{ auth()->user()->id }}" 
16                                    style="display: inline-flex;">
17                        </x-notification-center>
18                    </div>
19                </header>
20            @endif
21
22            <livewire:delivery-history />
23
24            <!-- Page Content -->
25            <main>
26                {{ $slot }}
27            </main>
28           
29</div>
30...

From the code above, you can see that we added the following:

1<div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
2      <x-notification-center app-id="MavBpIkktq7-" 
3                  subscriber-id="{{ auth()->user()->id }}" 
4                  style="display: inline-flex;">
5      </x-notification-center>
6</div>

Note: I have added the APP ID & Subscriber ID. The value of the APP ID is from the Novu Settings dashboard while the Subscriber ID is the ID of the logged in user.

Now you should have something like this on your dashboard showing the notification bell:

Trigger real-time notifications in your Laravel app

Open up app/Livewire/DeliveryHistory.php file. Here, we will add Novu code to trigger notification when a new delivery status is entered.

Add the code to the submitStatus() function like so:

1public function submitStatus()
2{
3        PackageSent::dispatch(auth()->user()->name, $this->status, Carbon::now());
4
5        /**
6         *  Trigger Novu to fire the in-app notifications
7         */
8        novu()->triggerEvent([
9            'name' => 'laravel-in-app-notifications',
10            'payload' => [
11                'deliveryStatus' => $this->status,
12                'deliveryHandler' => auth()->user()->name
13            ],
14            'to' => [
15                'subscriberId' => auth()->user()->id,
16            ]
17        ])->toArray();
18
19        $this->reset('status');
20}

The value of the name is the workflow trigger ID. Open up the Novu workflow we created on Novu dashboard, you will be able to identify the trigger ID like so:

Next, we included both deliveryStatus and deliveryHandler as payload items in the trigger code call. This allows our workflow to receive and display them as part of the notification content in the Notification Center.

Finally, we add the ID of the subscriber that we want to see the real-time notification when it has been triggered. This should always be the ID of the logged-in-user so that they can see the notification once it comes into the app.

One more thing…

Open up routes/channel.php and modify it to the code below:

1<?php
2
3use Illuminate\\Support\\Facades\\Broadcast;
4
5Broadcast::channel('delivery', function ($user) {
6    return true;
7});

We need to do this (return true always regardless of whoever is logged in) else we won’t be allowed to enter a status because the user that is logged in is no longer of ID 1.

Reload your app and attempt to add a status. You’ll notice the notification appear in real time in the Notification Center. It’s quick, instantaneous, and visually pleasing!

You can try different things in the Notification center pop up:

  • You can mark an individual message as read.
  • You can delete one individual message
  • You can mark all as read at once.

Novu makes it a breeze to add as many notification channels as possible without having to incorporate the logic of each notification provider. Write once, run as many channels as possible!

Check out the documentation on all the many things you can do with Novu’s Notification Center

Conclusion

We’ve covered how to use Laravel Reverb, from setup and configuration to building a real-time app. You’ve also learned how to leverage Novu in setting up effective, scalable real-time in-app notifications.

Laravel and Novu are powerful tools. When combined, they provide everything you need to build fast, robust, scalable, and real-time apps. I’m excited to see your next app.

If you have any questions, feel free to explore our documentation and quickstarts. You can also find me on Discord and Twitter. Don’t hesitate to reach out.

Related Posts

category: How to

Case Study: How Novu Migrated User Management to Clerk

Discover how Novu implemented Clerk for user management, enabling features like SAML SSO, OAuth providers, and multi-factor authentication. Learn about the challenges faced and the innovative solutions developed by our team. This case study provides insights into our process, integration strategies that made it possible.

Emil Pearce
Emil Pearce
category: How to

How to Implement React Notifications — Including Examples, Alerts, and Libraries

Learn how to implement effective notifications in React applications. Explore the differences between stateless and stateful notifications, and discover the best libraries and practices for enhancing user engagement and information delivery in your React projects.

Emil Pearce
Emil Pearce
category: How to

How Product-Development Friction Ruins User Experience with Notifications

Discover how friction between product and development teams can lead to poor notifications and damage your user experience. Learn strategies to overcome these challenges and enhance your notification system for better user engagement.

KMac Damaso
KMac Damaso