当我在Laravel广播中使用toOthers的呼叫时出现服务器错误

时间:2019-10-21 14:05:01

标签: laravel

宣布已发布新活动

请使用下面的代码,如果我使用event()可以正常工作,但是如果我添加toOthers则会给我一个错误提示,为什么?

Route::post('/messages', function(){
    $user = Auth::user();

    $message = $user->messages()->create([
        'message' => request()->get('message')
    ]);

    //Announce that new event have been posted
    broadcast(new MessagePosted($message, $user))->toOthers;

    return ['status' => 'OK'];

})->middleware('auth');

3 个答案:

答案 0 :(得分:1)

toOthers()是一个函数而非属性

broadcast(new MessagePosted($message, $user))->toOthers();

来自the docs

但是,broadcast函数还公开了toOthers方法,该方法使您可以从广播的收件人中排除当前用户:

broadcast(new ShippingStatusUpdated($update))->toOthers();

vendor/laravel/framework/src/Illuminate/Broadcasting/PendingBroadcast.php第41行的the source

public function toOthers()
{
    if (method_exists($this->event, 'dontBroadcastToCurrentUser')) {
        $this->event->dontBroadcastToCurrentUser();
    }

    return $this;
}

希望这会有所帮助

答案 1 :(得分:0)

将此添加到Others();

广播(新MessagePosted($ message,$ user))-> toOthers();

答案 2 :(得分:0)

Route::post('/messages', function(){

    $user = Auth::user();
    $message = $user->messages()->create([
        'message' => request()->get('message')
    ]);    

    broadcast(new MessagePosted($message, $user))->toOthers();

    return ['status' => 'OK'];
})->middleware('auth');