Web Application

How to Build a Real-Time Web Notification in Laravel using Pusher?

Imagine you are developing a web application and you need to implement notification functionality which is displaying real-time what do you think first to implement that functionality? Taking records from a database with certain framework queries, Right? But getting notifications from the database with database queries can be a little slower to show notifications, and for that users have to refresh the page every time to see new notifications. What if there are options in the market that give us notifications without refreshing the page? Sounds interesting right? That thing can be achieved by Laravel Pusher.

What is Laravel Pusher?

Pusher is a hosted service that makes it easy to implement a real-time web application or mobile application inefficiently way.

Pusher sits is a real-time layer between servers and clients. It’s maintains tenacious connections to the clients – over the WebSocket and if possible and falling back to HTTP-based relatedness – so that as soon as your servers fetch new data that your server wants to push to the clients they can do, instantly via Laravel Pusher.

In this blog, we will explain to you how can we build real-time notifications in small applications.

First of all, you need to sign up for pusher for a free account via pusher.com/signup.

Then you need to create your application as seen in the picture below.

Once you have done with creating your application you will land within an “App Keys” page for your application.

For implementing this feature all you need to do is take “App Credentials”.

  • app_id
  • key
  • Secret
  • Cluster

On the Pusher login page after creating an application you can see your credentials in App Keys Tab as you can see in the below image.

Setting Up Your Laravel Application:

Now you can create a new Laravel application by running the below command in your terminal. Make sure the composer is already installed in your system.

laravel new laravel-real-time-notifications

After that we need to install Pusher SDK, You can install it via the below command.

Composer require pusher/pusher-php-server

When that thing is done, we need to configure Pusher in Laravel as a broadcaster driver. For that need to open the .env file and update the values which shown below.

BROADCAST_DRIVER=pusher
// Set your Pusher credentials in .env file
PUSHER_APP_ID=XXXXX
PUSHER_APP_KEY=XXXXXXX
PUSHER_APP_SECRET=XXXXXXX

Now Open config/app.php file and uncomment BroadcastServiceProvider::Class.

Creating Application in Your System:

Now that we are done with the Pusher configuration, let’s create our application. First, we have to create an Event class that would broadcast to Pusher from our Laravel application. Remember events can be fired from anywhere in the application.

php artisan make:event PostLiked

Above command will create a new class in the app/Events directory. Open the file and update to the following below:

namespace AppEvents;
use IlluminateQueueSerializesModels;
use IlluminateFoundationEventsDispatchable;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateContractsBroadcastingShouldBroadcastNow;
class PostLiked implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $username;
    public $message;
/**
* Create a new event instance.
*
* @return void
*/    public function __construct($username)
    {
    $this->username = $username;
    $this->message = "{$username} liked your status";
    }
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/    public function broadcastOn()
    {
    return ['post-liked'];
    }
}

Above, we have implemented the ShouldBroadcastNow interface and this tells that this event should be broadcasted using whatever driver we have set in the config file.

In our code, we have a constructor that accepts two parameters, username, and verb. We will get back to this later on. We assigned these variables to class properties named the same way. It is important to set the visibility of the properties to the public; if you don’t, the property will be ignored.

Lastly, we set the channel name to broadcast on.

Creating Application Views:

We will be going to create a single view where you can see a navbar with a notification icon. The icon will be changed when new notifications are created without refreshing the page. The notifications are passing in this blog by design.

Open the welcome.blade.php file and replace it with the HTML code Click here.

This is commonly a lot of Bootstrap sound, so we will separate the important parts, mostly Javascript. We include the Pusher library, and then we added the javascript block that does the real-time counting thing. Have look at some snippets of the javascript block:

// Enable pusher logging -  No need to add in Production
// Pusher.logToConsole = true;
// Initialization the Pusher JS library
var pusher = new Pusher('API_KEY_HERE', {
  encrypted: true
});
// Subscribe to the channel we specified in our Laravel Event
var channel = pusher.subscribe('post-liked');
// Bind a function to an Event (the full Laravel class)
channel.bind('App\Events\PostLiked', function(data) {
  // this is called when the event notification is received...
});

The code above just initializes the Pusher JS library and subscribes to a channel. It then sets a callback to call when the event broadcasted is received on that channel.

Testing our Setup:

Finally, to test our setup, we will create a route that manually calls the event. If everything works as expected, we will get a new notification anytime we hit the route. Let’s add the new route:

Route::get('test', function () {
event(new AppEventsPostLiked('Someone'));
return "Event has been sent!";
});

Now we can start a PHP server using Laravel so we can test our code to see if it works.

$ php artisan serve

Conclusion

In this article, we have been able to understand the functionality of Laravel Pusher to create an easy and efficient real-time notification into web applications. This is just basic of what we can done using Laravel Pusher. We can do many more things like updating real-time analytics count using Laravel Pusher.

If you have any queries regarding real-time web notification using pusher in Laravel, you can freely contact us and we will give our guidance or hire Laravel developer.

Recent Posts

  • OTA

The Rise of Dynamic Packaging in OTA

Using dynamic packaging technology, one can encapsulate flights, accommodation, cars,…

  • UI/Ux Design

Unlocking Digital Success with UX/UI Design

In today’s contemporary era of accelerated digital evolution, the importance…

  • UI/Ux Design

Why UI Design is Important for Your Website? A Step Towards Way Superior UX

The fact is that in today’s internet environment the only…