Laravel Echo を使ってnotification の実装 with Pusher

Laravel Echo : A JavaScript library that makes it painless to subscribe to channels and listen for events broadcast by Laravel. 

 

Installation

composer require pusher/pusher-php-server "~3.0"

参考:

laravel.com

Problem 1
- Installation request for pusher/pusher-php-server ~3.0 -> satisfiable by pusher/pusher-php-server[3.0.0].
- pusher/pusher-php-server 3.0.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.

ここでエラーが出たら → sudo apt-get update

                                         sudo apt-get install php7.1-curl

curl インストール後、apacheを再起動

npm install --save laravel-echo pusher-js

 

Laravel Echo setting up

@resources/assets/js/bootstrap.js から以下をコメントアウトから外す

import Echo from "laravel-echo"

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'your-pusher-key',
cluster: 'your-cluster' });

your-pusher-key, your-cluster に pusher アカウント情報を挿入

@config/app.php から以下をコメントアウトから外す

/*
* Application Service Providers...
*/

App\Providers\BroadcastServiceProvider::class,

 

Create a migration for the notifications table

php artisan notifications:table

php artisan migrate

 

 Create a new notification class

php artisan make:notification NewFriendRequest

 

Pusher setting up

Pusher の Your App/Overview ページの下部にある app_id, key, secret, cluster を記入

@config/broadcasting.php

'connections' => [

'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => 'ap1',
'encrypted' => true
],
],

@.env

BROADCAST_DRIVER=pusher  // Kati#25

 

PUSHER_APP_ID=

PUSHER_APP_KEY=

PUSHER_APP_SECRET=

 --------------------------------------------------------------------------------------------------------kati#21

Notification setting up @notification/NewFriendRequest.php

public $user;

/**
* Create a new notification instance.
*
* @return void
*/
public function __construct($user)
{
$this->user = $user;
}

-> User::find($id)->notify(new \App\Notifications\NewFriendRequest(Auth::user()) from FriendshipController

------------------------------------------------------------------------------------------------------------

via method that determines on which channels the notification will be delivered. Out of the box, notifications may be sent on the maildatabasebroadcastnexmo, and slack channels.

 

public function via($notifiable)
{
return ['broadcast', 'database'];
}

 ----------------------------------------------------------------------------------------------------------------

/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/

public function toMail($notifiable)
{
return (new MailMessage)
->line('You received a new frined request from' . $this->user->name )
->action('View profile', route('profile', ['user-id'=> $this->user->id ]))
->line('Thank you for using our application!');
}

----------------------------------------------------------------------------------------------------------------

/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
'name' => $tihs->user->name,
'message' => $this->user->name . 'sent you a friend request.'
];
}

----------------------------------------------------------------------------------------------------------------

Sending Notification

@FriendshipsController.php

public function add_friend($id)
{
//sending notifications, emails, broadcasting.
  $resp = Auth::user()->add_friend($id);
  User::find($id)->notify(new \App\Notifications\NewFriendRequest(Auth::user()) );
  return $resp;
}

notification を Auth user から $id に送る。

 ------------------------------------------------------------------------------------------------------kati#23

参考:

laravel.com

Frontend setting up (private channel へ接続するためにAuth id を passing)

.notification 以降: サーバーから受けた notification を handling

@Notification.vue

<template>
<div>

</div>
</template>

<script>
export default {
mounted() {
this.listen();
},
props: ['id'],
methods: {
  listen() {
    Echo.private('App.User.' + id)
      .notification( (notification) => {
        alert('New Notification');
        console.log(notification);
    })
  }
}
}
</script>

 

親 component から props を notification.vue へ passing 

@app.blade.php

@yield('content')
@if(Auth::check())
  <notification :id="{{ Auth::id() }}"></notification>
@endif

 

console にログ出し

@resources/assets/js/bootstrap.js

Pusher.log = function(message)
{
window.console.log(message)
}

上記を追記

 

接続の確認

f:id:monteecristoo:20171018203145j:plain

 Pusher 側からリクエス

f:id:monteecristoo:20171018222413j:plain

Send event 後、Event sent successfully.  と表示され、

f:id:monteecristoo:20171018223106j:plain 

------------------------------------------------------------------------------------------------------kati#24

別のユーザーが接続された状態で friend request を受けるとコンソールに下記が表示

 

f:id:monteecristoo:20171026222800j:plain

 

------------------------------------------------------------------------------------------------------kati#25