Tutorial simples de notificações no Laravel 5.6
- Ubuntu-PHPS Docker Image
$ docker pull lissonpsantos2/ubuntu-phps
$ docker run -v /caminho/completo/project:/home/project-folder -p 8080:80 -it lissonpsantos2/ubuntu-phps
$ selectphp 7.1
- Criar uma conta no Pusher
- Criar um canal
No console do Docker
$ cd /home/project-folder
$ mkdir notifications-class
$ cd notifications-class
$ composer create-project --prefer-dist laravel/laravel notifications
$ cd notifications
$ npm install --save laravel-echo pusher-js cross-env
$ composer require pusher/pusher-php-server
- Teste a instalação
$ apachelinker /home/project-folder/notifications-class/notifications/public
- Configure o moloquent
No seu editor
-
Atualize o seu arquivo
.env
utilizando as credenciais de sua base de dados e com as credenciais do canal criado no PusherDB_CONNECTION=mongodb DB_HOST= DB_PORT= DB_DATABASE= DB_USERNAME= DB_PASSWORD= BROADCAST_DRIVER=pusher PUSHER_APP_ID= PUSHER_APP_KEY= PUSHER_APP_SECRET= PUSHER_APP_CLUSTER= MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}" MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
-
Abra o arquivo
/app/user.php
- Substitua a linha que contém o
use Authenticatable
poruse Jenssegers\Mongodb\Auth\User as Authenticatable;
- Substitua a linha que contém o
-
Abra o arquivo
/config/broadcasting.php
e emconnections
adicione'pusher' => [ 'driver' => 'pusher', 'key' => env('PUSHER_APP_KEY'), 'secret' => env('PUSHER_APP_SECRET'), 'app_id' => env('PUSHER_APP_ID'), 'options' => [ 'cluster' => env('PUSHER_APP_CLUSTER'), 'encrypted' => true, ], ],
-
Abra o arquivo
/config/app.php
e descomente a linhaApp\Providers\BroadcastServiceProvider::class
-
Abra o arquivo
/resources/assets/js/bootstrap.js
e descomente as linhas 47 até 56
De volta ao console do Docker no diretório do projeto
$ npm run dev
$ php artisan make:auth
$ php artisan migrate
$ php artisan make:notification StatusLiked
Voltando ao seu editor de texto
- Abra o arquivo
/app/notification/StatusLiked.php
-
Adicione a linha
use Illuminate\Notifications\Messages\BroadcastMessage;
no início do aquivo -
Modifique o construtor da classe
public function __construct($username) { $this->username = $username; $this->message = "{$username} liked your status"; }
-
Modifique o método
via
public function via($notifiable) { return ['broadcast']; }
-
Adicione o método
toBroadcast
public function toBroadcast($notifiable) { return new BroadcastMessage([ 'message'=>$this->message, 'user'=>auth()->user() ]); }
-
-
Abra o arquivo
/resources/view/layout/app.blade.php
-
Adicione ao início do seu arquivo as linhas abaixo, o jquery deve ser colocado antes do
<script src="{{asset('js/app.js')}}" defer></script>
e o bootstrap-notifications antes do<link href="{{asset('css/app.css')}}" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="/css/bootstrap-notifications.min.css"> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js" defer></script>
-
Troque a sua tag
<body>
por@if (Auth::check()) <body data-user-id="{{ Auth::user()->id }}"> @else <body> @endif
-
Dentro da tag
<ul class="navbar-nav mr-auto"></ul>
adicione<li class="nav-item dropdown dropdown-notifications"> <a href="#notifications-panel" class="nav-link dropdown-toggle" data-toggle="dropdown"> Notifications (<span data-count="0" class="notif-count">0</span>) </a> <ul class="dropdown-menu"> </ul> </li>
-
-
Abra o arquivo
/resources/assets/sass/app.scss
e adicione a classe.media-body { padding-left: 5.6px; }
-
Abra novamente o arquivo
/resources/assets/js/app.js
e adicione o código seguintevar notificationsWrapper = $('.dropdown-notifications'); var notificationsToggle = notificationsWrapper.find('a[data-toggle]'); var notificationsCountElem = notificationsToggle.find('span[data-count]'); var notificationsCount = parseInt(notificationsCountElem.data('count')); var notifications = notificationsWrapper.find('ul.dropdown-menu'); if (notificationsCount <= 0) { notificationsWrapper.hide(); } var updateNotifications = function (data) { var existingNotifications = notifications.html(); var avatar = Math.floor(Math.random() * (71 - 20 + 1)) + 20; var newNotificationHtml = ` <li class="notification active"> <div class="media"> <div class="media-left"> <div class="media-object"> <img src="https://api.adorable.io/avatars/71/`+ avatar + `.png" class="img-circle" alt="50x50" style="width: 50px; height: 50px;"> </div> </div> <div class="media-body"> <strong class="notification-title">`+ data.message + `</strong> <!--p class="notification-desc">Extra description can go here</p--> <div class="notification-meta"> <small class="timestamp">about a minute ago</small> </div> </div> </div> </li> `; notifications.html(newNotificationHtml + existingNotifications); notificationsCount += 1; notificationsCountElem.attr('data-count', notificationsCount); notificationsWrapper.find('.notif-count').text(notificationsCount); notificationsWrapper.show(); }; if($('body').data('user-id')){ Echo.private('App.User.' + $('body').data('user-id')) .notification((notification) => { console.log(notification.type); updateNotifications(notification); }); }
Faça o download do bootstrap-notifications e extraia o arquivo dentro de
/public/css
-
Abra o arquivo
/routes/web.php
e adicione a seguinte rotaRoute::get('/notify', function(){ Auth::user()->notify(new \App\Notifications\StatusLiked('Someone')); // Notification::send(Auth::user(), new \App\Notifications\StatusLiked('Someone')); return "Notification has been sent!"; });
De volta ao console do Docker
- Execute novamente o comando
npm run dev
- Com seu navegador, acesse o endereço
/register
e crie um novo usuário - Em outra aba/janela, acesse o endereço
/notify
e verifique se a notificação ocorreu na barra de navegação