【发布时间】:2021-07-15 09:06:22
【问题描述】:
我正在尝试使用 Laravel WebSockets 作为 socket 服务器 和 Laravel Echo 与 Events 进行一些实时推送通知.
当我在Channel 上执行此操作时,它工作正常,但现在我希望它发送到私人频道。
Channel('reservation.' . $this->random_key);
到
PrivateChannel('reservation.' . $this->random_key);
NewReservationEvent.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class NewReservationEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public $random_key;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($message, $user)
{
$this->message = $message;
$this->random_key = $user->random_key;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('reservation.' . $this->random_key);
}
public function broadcastAs()
{
return 'reservation.event';
}
}
routes/channels.php
<?php
use Illuminate\Support\Facades\Broadcast;
/*
|--------------------------------------------------------------------------
| Broadcast Channels
|--------------------------------------------------------------------------
|
| Here you may register all of the event broadcasting channels that your
| application supports. The given channel authorization callbacks are
| used to check if an authenticated user can listen to the channel.
|
*/
Broadcast::channel('App.Models.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
Broadcast::channel('reservation.{random_key}', function ($user, $random_key){
return true;
});
routes/web.php
Route::get('/sendEvent', function () {
$superAdmins = User::where('role', 'Super')->get();
foreach ($superAdmins as $superAdmin) {
$message = 'Reservation added by';
event(new NewReservationEvent($message, $superAdmin));
}
});
BroadcastServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes(['middleware' => ['auth', 'checkRole:Super,Admin,Customer']]);
require base_path('routes/channels.php');
}
}
这是我认为的Echo:
Echo.private('reservation.{{ auth()->user()->random_key }}')
.listen('.reservation.event', (e) => {
console.log(e.message);
$("#refreshThisDropdown").load(window.location.href + " #refreshThisDropdown");
$("#refreshThisDropdown").load(" #refreshThisDropdown > *");
toastr.success(e.message, "Hello there");
})
在 Channel 模式下一切正常,我想将其设为 private 以提高安全性。
【问题讨论】:
-
您在会话中的基础身份验证到基于令牌的身份验证?
-
是的,我用 auth 保护它。并创建检查角色中间件来访问一些路由
-
我发布了我的答案你能检查你是否设置了这个然后
/authapi 将自动点击授权 websocket 私人频道
标签: php laravel websocket pusher