如何将一些变量传递给Laravel 5.5中的事件? 我尝试了几种模式,但没有工作。这是我的代码。有人有什么建议吗? 基本上我需要通过socket更新关注者的数量。使用Redis和Socket.io的服务器也可以正常工作
Route::post('follow', function() {
$negozio = Input::get('id_azienda');
$followers = new \App\Models\Followers;
$followers->entry_by = \Session::get('uid');
$followers->id_azienda = $negozio;
$followers->save();
$this->variabili['negozio'] = $negozio;
$this->variabili['followers'] = $followers->count();
event(new \App\Events\Follow(), $this->variabili);
});
这是事件
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class Follow implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public $variabili;
public function __construct()
{
$this->data = array(
'count'=> $variabili['followers'],
'negozio'=> $variabili['negozio']
);
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return ['test-channel'];
}
}
答案 0 :(得分:1)
您可以在Follow Event类中将其作为Constructor的参数传递,如果您需要它作为公共字段,请执行以下操作:
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class Follow implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $data;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($variabili)
{
$this->data = array(
'count'=> $variabili['followers'],
'negozio'=> $variabili['negozio']
);
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return ['test-channel'];
}
}
以这种方式传递参数:
Route::post('follow', function() {
$negozio = Input::get('id_azienda');
$followers = new \App\Models\Followers;
$followers->entry_by = \Session::get('uid');
$followers->id_azienda = $negozio;
$followers->save();
$this->variabili['negozio'] = $negozio;
$this->variabili['followers'] = $followers->count();
event(new \App\Events\Follow($this->variabili));
});