目次
1. PusherでAppを作成
2. Viewを作成
resources/views/welcome.blade.phpを以下の内容に変更
<!DOCTYPE html>
<head>
<title>Pusher Test</title>
<script src="https://js.pusher.com/4.1/pusher.min.js"></script>
<script>
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
var pusher = new Pusher('xxxxxx', {
cluster: 'ap1',
encrypted: true
});
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
alert(data.message);
});
</script>
</head>
3. ビルトンサーバーで確認
ブラウザのコンソールでログが出る
Pusher : State changed : initialized -> connecting
pusher.min.js:8 Pusher : Connecting : {"transport":"ws","url":"wss://ws-ap1.pusher.com:443/app/xxxxxx?protocol=7&client=js&version=4.1.0&flash=false"}
pusher.min.js:8 Pusher : State changed : connecting -> connected with new socket ID xxxxxxxx
pusher.min.js:8 Pusher : Event sent : {"event":"pusher:subscribe","data":{"channel":"my-channel"}}
pusher.min.js:8 Pusher : Event recd : {"event":"pusher_internal:subscription_succeeded","data":{},"channel":"my-channel"}
pusher.min.js:8 Pusher : No callbacks on my-channel for pusher:subscription_succeeded
4. Pusherのライブラリをインストール
$ composer require pusher/pusher-php-server
5. 設定ファイルを編集
config/broadcasting.phpを編集
'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' => env('PUSHER_APP_ENCRYPTED'),
],
],
.envを編集
PUSHER_APP_ID=xxxxx
PUSHER_APP_KEY=xxxxx
PUSHER_APP_SECRET=xxxxx
PUSHER_APP_CLUSTER=xxxx
PUSHER_APP_ENCRYPTED=true
6. テストイベントの作成
コマンドからイベントの作成
$ php artisan make:event HelloPusher
イベントでShouldBroadcast Interfaceを継承する
チャンネル名をフロントと合わせる
コンストラクタでメッセージを受け取りセットする
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class HelloPusher implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return new Channel('my-channel');
}
public function broadcastAs()
{
return "my-event";
}
public function broadcastWith()
{
return [
'message' => 'Hello Pusher!!'
];
}
}
7. イベントのテスト
web.phpに下記を追記
Route::get('/hello', function(){
event(new \App\Events\HelloPusher);
});
他のブラウザで/を開いている時に/helloをブラウザで開いてアラートが表示されればOK。