Setup Notifications For Subscribed Users

Setup Notifications For Subscribed Users

In the last tutorial, we saw how to set up the ability for a user to subscribe to a thread. So what does that mean for the user? Well, if they are subscribed to the thread, then they likely would like to stay up to date with any new replies or activity on that thread. In this tutorial, we’ll look at how to set up Notifications. For example, any time the thread gets a new reply, we could automatically send an email or simply populate a notifications component on the website itself. Let’s see how to set up this new feature now.

Preparing Notifications For A Subscribed User

We are going to lean on the built in Notifiable trait which Laravel uses to set up all kinds of notifications. In addition, artisan has a tool to set up the scaffolding needed to get this working.

vagrant@homestead:~/Code/forumio$ php artisan help notifications:table

  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
      --env[=ENV]       The environment the command should run under
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

  Create a migration for the notifications table

Ok, so let’s go ahead and run that command to get started, as well as migrate the database.

vagrant@homestead:~/Code/forumio$ php artisan notifications:table
Migration created successfully!
vagrant@homestead:~/Code/forumio$ php artisan migrate
Migrating: 2018_02_21_171105_create_notifications_table
Migrated:  2018_02_21_171105_create_notifications_table

Visiting the database now shows us a new notifications table that has all the fields needed to get started working with notifications. We can now use this table for notifications to subscribers, or perhaps notifications to mentioned users.
laravel notifications database table

Adding A Notification Class

Setting up the database table is the first part of setting up notifications, creating a notification class is the next step. There is also an artisan command to help with that so let’s go ahead and make use of it. We will create a ThreadWasUpdated notification class.

vagrant@homestead:~/Code/forumio$ php artisan make:notification ThreadWasUpdated
Notification created successfully.

This sets up a new Notifications directory in the project, and the new class if placed inside.
notfications folder created

You’ll need to update the contents of the new file to contain this code.

A ThreadSubscription belongs to a user, so we need to update the ThreadSubscription model to reflect that. While we are at it, we can also add a thread relationship, and a notify() method like so.

Notifications Need Endpoints

We’ll need to add a couple of routes to the web.php file to support getting and deleting notifications.

This means we also need a new controller named UserNotificationsController with an index() and destroy() method in place.

vagrant@homestead:~/Code/forumio$ php artisan make:controller UserNotificationsController
Controller created successfully.

We’ll add the following code as well.

Using Events For New Notifications

We can make use of events in Laravel to help with configuring notifications. Here is what we can do. First off, we’ll visit EventServiceProvider.php and make a couple of modifications.

With the $listen variable populated, we can now run the event generate command to build out the needed files for us automatically.

vagrant@homestead:~/Code/forumio$ php artisan event:generate
Events and listeners generated successfully!

This added two new directories with the associated files needed.
event generate made new folders

We can populate the code as follows for both ThreadReceivedNewReply.php and NotifySubscribers.php.

Firing The New Event

Now, the notification should be created when a new reply is added. We already have an addReply() method on the Thread model so let’s see how we can update that method to help us here. We will make use of events in Laravel to help us out.

But Does It Work?

We’re following along with Laracasts here, and we can use the test class that Jeff created to see if this all works. Here is the NotificationsTest class which takes care of all the needed tests for notifications.

Note that we need to update our Model Factory as well. In our case, we simply defined everything in the UserFactory.php file. Note the new addition.

Running the full suite in this class indicates that everything works!

vagrant@homestead:~/Code/forumio$ phpunit --filter NotificationsTest
PHPUnit 6.5.5 by Sebastian Bergmann and contributors.

...                                                                 3 / 3 (100%)

Time: 1.13 seconds, Memory: 10.00MB

OK (3 tests, 6 assertions)

In addition, we can test in the browser. We have a thread that user Nikola Tesla is subscribed to. We are going to log in as a different user, and post a reply to that thread. When that happens, then we should see a new notification in the database. In fact, it looks to be working in this scenario as well.
new reply added to subscribed thread

After the above reply was made, we check the database notifications table to see that a new notification has been generated.
a notification has been stored in the database

Rendering Notifications With VueJS

We will render the notification in the navigation bar on the right hand side. The component will only be rendered for a logged in user, so you can add the markup like so in nav.blade.php.

Knowing that we are now going to be building a new Vue component, we should boot up the watcher like so.

vagrant@homestead:~/Code/forumio$ yarn run watch-poll
yarn run v1.3.2
$ node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --watch-poll --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

Let’s register this new <user-notifications> component as a global component in app.js.

We can now create the component file like so.
vuejs notifications component

Within the component is the following markup.

We have everything in place now to take care of rendering notifications to the user. Just before this, we had the user Nikola Tesla subscribed to a thread of “The Weather is Beautiful Outside”. Then, in a different session, we logged in as a different user Tom and left a new reply. This means that Nikola Tesla should be notified of a new activity on that thread. Did it work?
notifications are rendered perfectly

Yes! We can see that when logged in as Nikola Tesla, a new notification is displayed in the navbar and it has a link directly to the thread in question. Fantastic.

Setup Notifications For Subscribed Users Summary

We now know how to both setup and render notification for users that are subscribed to a particular thread. This tutorial really goes hand in hand with the Subscription System Tutorial where we learned how to first give users the ability to subscribe to a thread. Now we are providing meaningful notifications for those subscribed users.