Ever wanted to get a real-time notification when there’s a new message in your inbox or a new user signs up to your site? Ever wondered how to? Well, you’re about to be in the know. Using Laravel and Pusher we’re going to set up quick notifications in a few minutes. Lets begin!

Tip: To follow this tutorial, you’ll need to be comfortable with using Laravel and basic JavaScript/jQuery.

For our notifications system, we’ll pretend to have a blog or website (you choose), that visitors can subscribe to and the administrator will see a little notification on the admin dashboard that some one new has subscribed.

First, we’ll setup a small Laravel app with a front page where users can subscribe and a dashboard for the site owner to see who’s subscribed.

Create a New Laravel App

We can create a new Laravel application using the Laravel installer:

laravel new notif-app

To keep things fast and easy, for our front page where our vistiors subscribe we’ll use the front page of the app welcome.blade.php which Laravel creates by default. On this page we’ll add a form with a field to enter emails and a Subscribe button.

<div class="subscription">
    <form class="form-inline" method="post" action="/subscribe" autocomplete="off">               
        <input type="hidden" name="_token" value="{{ csrf_token() }}">      
        <input type="email" class="elements form-control" name="email" placeholder="Email Address">
        <button class="elements btn btn-default">Subscribe</button>                        
    </form>
</div>

From the above we see we’ll need a Subscription model to store new subscribers. We create that easily using

php artisan make:model Subscription -m -c

The -m command is to create a migration file for the model and -c is to create a controller

Now that we have our model for storing subscriptions, and we want new subscriptions to be notifications, we’ll create a Notifications model using:

php artisan make:model Notification -m

In our SubscriptionController which we created earlier, we’ll add a method to add a new subscriber, which will handle the form submission.

First we add the route:

Route::post('/subscribe', 'SubscriptionController@add');

Then we fill up the controller:

<?php
namespace App\Http\Controllers;

use App\Notification;
use App\Subscription;
use App\Events\NewNotification;
use App\Http\Requests\SubscriptionRequest;

class SubscriptionController extends Controller
{
    public function add(SubscriptionRequest $request)
    {
        $newSubscription = Subscription::create([
              'email' => $request->email,
        ]);

        $notification = Notification::create([
            'type'      => 'New Subscription',
            'message'   => "{$newSubscription->email} subscribed " . $newSubscription->created_at->diffForHumans(),
        ]);
        event( new NewNotification( $notification ) );
        return redirect('/')->with('message', "You've successfully subscribed");
    }
}

Broadcasting the Event of a New Subscription Notification

As you can see above, I added event( new NewNotification( $notification ) ); in the SubscriptionController after a notification was created and passed the new Notification object in there. Let me explain:

Tip: you can refer to Laravel’s documentation on broadcasting here

First, we create an event say NewNotification and we’ll do that using artisan

php artisan make:event NewNotification

Then we implement the event to receive a new notification and well, broadcast it!

For an Event class to broadcasted, it’ll have to implement the `ShouldBroadcast interface; And you’ll need implementations of:

  • the broadcastAs method (specifies the event name for pusher to listen for)
  • the broadcastOn method (this specifies the channel to broadcast on) – ours is a public channel named admin and
  • the broadcastWith method (which returns an array of the data to be broadcast)
<?php
namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class NewNotification implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */

    /**
    * Notification Object
    * @var
    */
    public $notification;

    public function __construct($notification)
    {
        $this->notification = $notification;
    }

    /**
     * The event's broadcast name.
     *
     * @return string
     */
     public function broadcastAs()
     {
          return 'new_subscription';
     }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('admin');
    }

    public function broadcastWith()
    {
        return [
            'type'      => $this->notification->type,
            'message'   => $this->notification->message,
        ];
    }
}

Introducing Pusher

Setup Pusher account and app

Pusher is a service that provides real-time data functionality for implementation in sites and applications.

Sign up/sign in to pusher, then register a new app on the dashboard.

  • Fill in the name of your app
  • Select a cluster

Tip:the above are mandated fields

  • For this tutorial, I’ll be using Plain Vanilla Js for my front end implementation (so select that option on no. 3)
  • And of course Laravel as the backend, so select that on no. 4
  • And you can skip or fill the rest (its your boat to float)

Now, Laravel supports using pusher out of the box so we really don’t need to do much on that front. All we need to do is install the pusher library (via composer)

composer require pusher/pusher-php-server

and fill our Pusher details into our .env file

//in the .env file

BROADCAST_DRIVER=pusher

PUSHER_APP_ID=your_pusher_add_id
PUSHER_APP_KEY=your_pusher_app_key
PUSHER_APP_SECRET=your_pusher_app_secret

With this, Laravel will broadcast your event using pusher.

Showing our admin user the notification

Still in the spirit of keeping things short and easy, Laravel implements Authentication out of the box. This implementation provides us with routes and controllers for Registering and Logging in; and also provides us with a homepage for logged in user’s which will suffice as our admin dashboard. We leverage on this feature using:

php artisan make:auth

You can either seed into your users table or leverage on the register function of Laravel’s authenication feature to create an admin/owner user. (I chose the latter, perhaps I’m lazy)

Anyway, after you’ve

  • run the php artisan migrate command (this will run you migration scripts and create the appropriate tables for your models)
  • created your user (using the method of your choosing),

Tip: remember to edit and set your database configuration correctly in your .env file e.g.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

you can log the user in by calling the /login route in your browser. Once you’re logged in you’ll see the dashboard provided by Laravel.

We’ll amend this view a little to have a mail box icon on the navigation bar on which our notification will be displayed.

Tip: what we’re really amending is the layout because the navigation bar is included through app.blade.php in the resources/layouts directory

<ul>
    <li>
        <a href="#">
            <i class="fa fa-envelope"></i>
        </a>                                
        <span class="badge badge-notify {{ get_notification_class($notifications) }}">
         {{ $notifications }}
        </span>
    </li>
</ul>

Tip: I’ve used font awesome icons to create my mail box icon and created a badge to show my notification (the number of new subscribers) on yours you can implement this however is comfortable for you.

p.s. I’m using bootstrap and made some CSS modifications to get things the way i wanted them to look, but this is not very relevant to the main purpose of the tutorial so I will not include snippets of those. You can check those in the GitHub repo.

We’ll want the admin user to see a notification of all the unread notifications that were made while he/she was offline, so in our HomeController (a product of Laravel’s auth feature) we’ll do a little tweaking:

<?php
namespace App\Http\Controllers;

use App\Notification;
use Illuminate\Http\Request;

class HomeController extends Controller
{
   /**
    * Create a new controller instance.
    *
    * @return void
    */

    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
     public function index()
     {
          return view('home', [
              'notifications' => Notification::whereNull('viewed_at')->count(),
          ]);
     }
}

In the above code, we’ve made the HomeController make use of the Notification model, then passed a count of all un-viewed notifications to our home page.

Listening for Events

Now that we have written all the code to trigger our notification event, we’re left with actually displaying this event to the admin user on his/her dashboard.

  • We’ll include the pusher javascript library on the dashboard blade file (in my case in the layout blade being extended)

  • Next, we’ll write the actual code to listen to the event and display the notification in a javascript file.
var pusher = new Pusher('xxxxxxxx'); //the pusher app key
var channel = pusher.subscribe('admin');

channel.bind("new_subscription", function (data) { 
    if (data.type && data.message) {
        var current_notifications = $('.badge-notify').text() * 1;
        current_notifications += 1;
        $('.badge-notify').text(current_notifications);
        $('.badge-notify').show();
    }
});

The above code receives the payload data from the event, confirms its a valid payload, then increases the value on the notification badge.

Press Play

Conclusion

Laravel and Pusher work well together. If you’d like to make some improvements to the code above (there’s a lot to improve really) its available on Github. Also, if you’ve found other cool ways to use Laravel and Pusher for real time notifications, please leave a comment below.