Adv*_*ith 4 php events listener laravel
我正在创建一个新的应用程序,当创建文章时,将在该应用程序上显示通知。我尝试过使用事件和侦听器。
我的App\Article.php
...
protected $events = [
'created' => Events\ArticleWasPublished::class
];
...
Run Code Online (Sandbox Code Playgroud)
我的App\Providers\EventServiceProvider.php
protected $listen = [
'App\Events\ArticleWasPublished' => [
'App\Listeners\NotifyUsers',
],
];
Run Code Online (Sandbox Code Playgroud)
我的App\Events\ArticleWasPublished.php
...
use App\Article;
...
{
public $article;
public function __construct(Article $article)
{
$this->article = $article;
}
...
Run Code Online (Sandbox Code Playgroud)
我的App\Listeners\NotifyUsers.php
use App\Notification;
...
public function handle(ArticleWasPublished $event)
{
Notification::create([
'article_id' => $event->article->id,
'message' => 'A new Article was created'
]);
var_dump('Something');
}
Run Code Online (Sandbox Code Playgroud)
我在这里做错了什么?
我的问题是,当创建新文章时,不会创建新通知。我什至没有收到任何错误。
小智 5
据我所知,在 Laravel 5.5 中,该属性被命名为$dispatchesEvents,而不是$events。你用的是这个版本吗?
https://laravel.com/docs/5.5/eloquent#events
如果您要从旧版本迁移,这是您需要执行的更改之一:
模型 $events 属性
模型上的 $events 属性应重命名为 $dispatchesEvents。进行此更改是因为大量用户需要定义事件关系,这导致与旧属性名称发生冲突。