Instal·leu pusher:
$ composer require pusher/pusher-php-server
I creeu un esdeveniment i el dispareu a algun controlador, com per exemple:
class ShotOutController extends Controller { public function shotout() { // Venim de processar un formulari simple amb un botó (submit) i un textarea // 1) Validar formulari // 2) Persistència: migració/seed etc: shoutout/notification, models // 3) event(new ShotoutAdded($shoutout)); } }
On shoutout és un model Eloquent de la notificació que es vol enviar. Cal que definiu l'esdeveniment i definiu el canal on publicar (mètode broadcastOn) i que l'esdeveniment sigui de broadcast (implements ShouldBroadcast):
<?php namespace App\Events; use App\Events\Event; use App\Shoutout; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; class ShotoutAdded extends Event implements ShouldBroadcast { use SerializesModels; /** * @var Shoutout */ public $shoutout; /** * Create a new event instance. * * @return void */ShouldBroadcast public function __construct(Shoutout $shoutout) { // $this->shoutout = $shoutout; } /** * Get the channels the event should be broadcast on. * * @return array */ public function broadcastOn() { return ['shoutout-added']; } }
IMPORTANT: El atribut shoutout ha de ser públic per tal que sigui serialitzat per Laravel correctament al enviar-lo pel canal pusher
Resources:
var notifyUser = function (data) { var data = data.shoutout; if (! ('Notification' in window)) { alert('Web Notification is not supported'); return; } Notification.requestPermission(function(permission){ var notification = new Notification('@'+ data.handle +' said:', { body: data.content, icon: document.getElementById('site_image').content }); }); var loadPusher = function (){ Pusher.log = function(message) { if (window.console && window.console.log) { window.console.log(message); } }; var pusher = new Pusher(document.getElementById('pusher_key').content); var channel = pusher.subscribe('shoutout-added'); channel.bind('App\\Events\\ShoutoutAdded', notifyUser); }; }
Resources: