TechnologyWeb 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.

Create channel app

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

See also  7 Best Practices for Data Migration and Data Security in Cloud

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.

Pusher login page

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.

Hire professional Laravel developers for your next project.

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.

See also  How to Send Email Using Queue in Laravel?

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.

See also  The Changing Face of Travel Agency Business with Travel Portal

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
Connect with expert Laravel developers to develop web application for your business.

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.

lets start your project

Related Articles