2017-09-14 175 views
0

我爲我的應用設置了Pusher和Laravel Echo,以通知用戶某些事件觸發。推送器不在私有通道上廣播-PHP/Laravel

我已經測試過,看看安裝程序是否在「公共頻道」上播放,併成功地看到這是有效的。

這裏是事件本身:

class ItemUpdated implements ShouldBroadcast 
{ 
    use Dispatchable, InteractsWithSockets, SerializesModels; 

    public $item; 

    public function __construct(Item $item) 
    { 
     $this->item = $item; 
    } 

    public function broadcastOn() 
    { 
     return new Channel('items'); 
    } 
} 

公共頻道:

Broadcast::channel('items', function ($user, $item) { 
    return true; 
}); 

應用程序/資源/資產/ JS/bootstrap.js:

import Echo from 'laravel-echo'; 
window.Pusher = require('pusher-js'); 

window.Echo = new Echo({ 
    broadcaster: 'pusher', 
    key: 'my_key', 
    cluster: 'eu', 
    encrypted: true 
}); 

而Laravel回聲登記:(它是在我的主佈局的「頭部」部分,事件觸發視圖從中延伸。)

<head> 
<meta charset="utf-8"> 


<meta name="csrf-token" content="{{ csrf_token() }}"> 

<script src="{{ asset('js/app.js') }}"></script> 

<script> 
    window.Laravel = {'csrfToken': '{{csrf_token()}}'} 

    window.Echo.channel('items') 
    .listen('ItemUpdated', function(e) { 
     console.log("It is working:)"); 
    }); 

</script> 
</head> 

現在,這種設置適用於公共頻道廣播,但是當我嘗試在私人頻道播出,我得到

//updated "ItemUpdated" event broadcastOn() method 
    public function broadcastOn() 
    { 
     return new PrivateChannel('items'); 
    } 

//updated laravel echo registering 
<script> 
window.Laravel = {'csrfToken': '{{csrf_token()}}'} 

window.Echo.private('items') 
.listen('ItemUpdated', function(e) { 
    console.log("It is working:)"); 
}); 

//console logged error 
Pusher couldn't get the auth user from :myapp 500 

我已經檢查了即將離任的網絡請求從開發者控制檯並找出推送者正試圖「POST」到

http://localhost:8000/broadcast/auth 

但它得到一個500錯誤代碼。

認爲這可能有助於找出問題。

我該怎麼辦?

+0

這是一個'500'錯誤。檢查你的日誌。 – Ohgodwhy

+0

是的,但由於我的服務器在公共廣播中正常工作,我不知道問題出在哪裏 – QnARails

+0

如上所述。檢查你的日誌。他們說什麼? – Ohgodwhy

回答

1

所以我想通了如何實現私人通道聽,並得到它的工作。

我的錯誤是在通配符選擇。

我告訴它使用通過身份驗證的用戶ID作爲通配符而不是應用更改的項目ID。

因此,下面的這個渠道註冊總是返回錯誤並導致Pusher投出500個無法找到的auth。

Broadcast::channel('items.{item}', function ($user, \App\Item $item) { 
    return $user->id === $item->user_id; 
}); 

所以,這裏是工作版本:正在播出

事件:

//ItemUpdated event 

class ItemUpdated implements ShouldBroadcast 
{ 
    use Dispatchable, InteractsWithSockets, SerializesModels; 

    public $item; 

    public function __construct(Item $item) 
    { 
     $this->item = $item; 
    } 

    public function broadcastOn() 
    { 
     return new PrivateChannel('items.'.$this->item->id); 
    } 
} 

頻道註冊:

app\routes\channels.php  

Broadcast::channel('items.{item}', function ($user, \App\Item $item) { 
    return $user->id === $item->user_id; 
}); 

Laravel回聲登記:

<head> 

<meta name="csrf-token" content="{{ csrf_token() }}"> 


<script> 
    window.Laravel = {'csrfToken': '{{csrf_token()}}'} 

    window.Echo.private(`items.{{{$item->id}}}`) 
    .listen('ItemUpdated', function(e) { 
     console.log("It is working!"); 
    }); 

</script> 

謝謝大家的指針。