Laravel如何从控制器到事件监听器获取数据?



我正在做待办事项页面。我想记录所有的任务过程到数据库,如'Walk">";但是我不能得到'walk'数据给听众。它说">未定义属性:AppEventsToDoEditEvent::$message"(这里$message表示待办任务。)我该怎么办?

控制器

#Controller
public function arrangeTask($id)
{
$task = ToDoTask::find($id);
if ($task->completedTask == false){
$task->completedTask = true;
}
else{
$task->completedTask = false;
}
$event = new UserLog();
$event->message = $task->TaskName;
event(new ToDoEditEvent($event));
$task->save();
return redirect()->route('home');
}

#EditEvent
class ToDoEditEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $userLog;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(UserLog $userLog)
{
$this->userLog = $userLog;
}
/**
* Get the channels the event should broadcast on.
*
* @return IlluminateBroadcastingChannel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}

Listener(已经配置EventServiceProvider staff)

class ToDoEditListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param  ToDoEditEvent  $event
* @return void
*/
public function handle(ToDoEditEvent $event)
{
$currentTimestamp = Carbon::now()->toDateTimeString();
$addTask = DB::table('user_logs')->insert([
'message'=>$event->message,
'context'=>'Düzenleme',
'extra'=>Auth::user()->name,
'created_at'=>$currentTimestamp,
'updated_at'=>$currentTimestamp
]
);
return $addTask;
}
}
<<p>用户模型/strong>
class UserLog extends Model
{
use HasFactory;
protected $guarded = [];
protected $dispatchesEvents = [
"message" => ToDoCreatedEvent::class
];
}
public function __construct(UserLog $userLog)
{
$this->userLog = $userLog;
}

而不是

public function __construct(ToDoTask $userLog)
{
$this->userLog = $userLog;
}

这意味着如果你使用任务类而不是事件,它可以工作。同时,

#Controller
public function arrangeTask($id)
{
$task = ToDoTask::find($id);
if ($task->completedTask == false){
$task->completedTask = true;
}
else{
$task->completedTask = false;
}
$event = new UserLog();
$event->message = $task->TaskName;
event(new ToDoEditEvent($event));
$task->save();
return redirect()->route('home');
}

如果您使用below而不是up,您可以访问任务人员中的所有变量。

#Controller
public function arrangeTask($id)
{
$task = ToDoTask::find($id);
if ($task->completedTask == false){
$task->completedTask = true;
}
else{
$task->completedTask = false;
}
event(new ToDoEditEvent($task));
$task->save();
return redirect()->route('home');
}

最新更新