This project is a basic example of how real time notification work in laravel, In this exmaple we have updated our UI when a notification is broadcasted by listening to it using web sockets. Here is some of the Laravel packages which we have used in this project:
- Laravel Events
- Laravel Notifications
- Laravel Broadcasting
- Laravel Web Sockets
Websockets are used to implement realtime, live-updating user interface in may modern apps like fb, twitter etc. When there any kind of update in server a message is typically send over a websocket conection to be handled by the client. Websockets helps to continually pulling server data in order to change the UI on every time when there is any kind of changes in the server side.
composer require pusher/pusher-php-server "~4.0"
BROADCAST_DRIVER=pusher
For Localhost setup.... (We are not using pusher here. just using pusher key inordre to use websockets).
PUSHER_APP_ID=local
PUSHER_APP_KEY=local
PUSHER_APP_SECRET=local
PUSHER_APP_CLUSTER=mt1
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'encrypted' => true,
'host' => '127.0.0.1',
'port' => 6001,
'scheme' => 'http'
],
uncomment this line in the config/app.php. Its very important for using the service of broadcasting in our app.
App\Providers\BroadcastServiceProvider::class,
now we will create and event and implements it with ShouldBroadcast. [implements ShouldBroadcast] important*.
php artisan make:event SampleBroadcastEvent
------------------------------------- Now the Receiving Broadcast Part ---------------------------------------
npm install --save-dev laravel-echo pusher-js
import Echo from "laravel-echo";
window.Pusher = require("pusher-js");
window.Echo = new Echo({
broadcaster: "pusher",
key: process.env.MIX_PUSHER_APP_KEY,
// cluster: process.env.MIX_PUSHER_APP_CLUSTER,
wsHost: "127.0.0.1",
wsPort: 6001,
forceTLS: false,
disableStats: true,
});
npm run dev
Note: for private channel, make sure you have CSRF linked to your header and your are logged in. means authenticated user.
<script>
Echo.private('testChannelName')
.listen('SampleBroadcastEvent', (e) => {
console.log(e);
});
</script>
Next to the broadcast routes, the BroadcastServiceProvider also activates the routes/channels.php file. Here is where we define who is allowed to access a private channel.
Broadcast::channel('testChannelName', function ($user) {
return true;
});
------------------------------------- Now the Notifications Part ---------------------------------------
php artisan make:notification RealTimeNotification
return ['broadcast'];
public function toBroadcast($notifiable): BroadcastMessage
{
return new BroadcastMessage([
'message' => "$this->message (User $notifiable->id)"
]);
}
MIT license.