Real-time notifications are crucial to any application (web or mobile) and Pusher is one of the most popular services which helps you deliver real-time notifications to your applications. I have used Pusher on several projects and it was a delight to implement. It is a simple and straightforward process. So let us see how we can implement real-time notifications in this laravel pusher tutorial.
Prerequisites:
- Sign up for a new account on Pusher.com and obtain your
app_id
,key
,secret
and also note down yourcluster
. These can be found in the App Keys section of your Pusher dashboard.
Setup your Laravel project:
- See the official Laravel documentation for installation instructions on Laravel.
- Require the
pusher-php-server
package in your laravel project usingcomposer
. - We will dump the composer autoload so our newly required package will be loaded by composer.
- Create a
PusherController
which will hold our notification logic. We will also add anotify
route to our fileweb.php
, using which we will send notification using Pusher. - Add the below code to
sendNotification()
method ofPusherController
.- Here we first include Pusher (
use Pusher\Pusher
) in ourPusherController
and set ourcluster
andencryption
keys in anoptions
array. We then create a newPusher
object by providing our credentials and also passing in our$options
array. - We can then publish to a channel and also specify a channel name. I have used
nofify
as thechannel name
andnotify-event
as theevent name
and these can be changed to any name you want. But remember to use the samechannel name
andevent name
in your front-end client.
- Here we first include Pusher (
- Define a view route in your
web.php
file. Thehome.blade.php
will hold ourjs
code and will display an alert whenever a new notification is published to our channel. - Add the code below to
home.blade.php
. - That’s it! open up a new tab and visit
www.your_domain.dev/notify
while having thewww.your_domain.dev/home
open in another tab and you should see the alert!.
Of course, this was just a basic demo and you may use this in a more practical setting such as a notification widget or something like that but the core concept will remain the same. The source code for this tutorial is available on GitHub.
If you liked this laravel pusher tutorial then you might also like to read other ways of sending notifications in Laravel and be sure to leave any comments or ask any questions you might have in the comment section below!.
That's amazing informative post, I want to add one more thing, If you want to make your web visitor to your subscriber then you should definitely check gravitec lifetime deal Best push notification for website ever.
ReplyDeleteIt is quite beneficial, although think about the facts when it reaches this target. 900 seconds into minutes
ReplyDelete