Php 未触发laravel model$事件
我正在创建一个新的应用程序,当创建一篇文章时,它将显示一个通知。我尝试过使用事件和侦听器 我的Php 未触发laravel model$事件,php,laravel,events,listener,Php,Laravel,Events,Listener,我正在创建一个新的应用程序,当创建一篇文章时,它将显示一个通知。我尝试过使用事件和侦听器 我的App\Article.php ... protected $events = [ 'created' => Events\ArticleWasPublished::class ]; ... protected $listen = [ 'App\Events\ArticleWasPublished' => [ 'App\Listeners\Notif
App\Article.php
...
protected $events = [
'created' => Events\ArticleWasPublished::class
];
...
protected $listen = [
'App\Events\ArticleWasPublished' => [
'App\Listeners\NotifyUsers',
],
];
...
use App\Article;
...
{
public $article;
public function __construct(Article $article)
{
$this->article = $article;
}
...
use App\Notification;
...
public function handle(ArticleWasPublished $event)
{
Notification::create([
'article_id' => $event->article->id,
'message' => 'A new Article was created'
]);
var_dump('Something');
}
我的App\Providers\EventServiceProvider.php
...
protected $events = [
'created' => Events\ArticleWasPublished::class
];
...
protected $listen = [
'App\Events\ArticleWasPublished' => [
'App\Listeners\NotifyUsers',
],
];
...
use App\Article;
...
{
public $article;
public function __construct(Article $article)
{
$this->article = $article;
}
...
use App\Notification;
...
public function handle(ArticleWasPublished $event)
{
Notification::create([
'article_id' => $event->article->id,
'message' => 'A new Article was created'
]);
var_dump('Something');
}
我的App\Events\ArticleWasPublished.php
...
protected $events = [
'created' => Events\ArticleWasPublished::class
];
...
protected $listen = [
'App\Events\ArticleWasPublished' => [
'App\Listeners\NotifyUsers',
],
];
...
use App\Article;
...
{
public $article;
public function __construct(Article $article)
{
$this->article = $article;
}
...
use App\Notification;
...
public function handle(ArticleWasPublished $event)
{
Notification::create([
'article_id' => $event->article->id,
'message' => 'A new Article was created'
]);
var_dump('Something');
}
我的App\Listeners\NotifyUsers.php
...
protected $events = [
'created' => Events\ArticleWasPublished::class
];
...
protected $listen = [
'App\Events\ArticleWasPublished' => [
'App\Listeners\NotifyUsers',
],
];
...
use App\Article;
...
{
public $article;
public function __construct(Article $article)
{
$this->article = $article;
}
...
use App\Notification;
...
public function handle(ArticleWasPublished $event)
{
Notification::create([
'article_id' => $event->article->id,
'message' => 'A new Article was created'
]);
var_dump('Something');
}
我做错了什么
我的问题是,当创建新文章时,不会创建新通知。我甚至没有收到任何错误。据我所知,在Laravel 5.5中,属性名为
$dispatchesEvents
,而不是$events
。你正在使用这个版本吗
如果要从旧版本迁移,这是需要进行的更改之一:
模型$events属性
模型上的$events属性应重命名为
$dispatchesEvents。做出此更改是因为有大量
需要定义事件关系的用户,这会导致
与旧属性名称冲突
是的,我使用的是Laravel 5.5。谢谢你的回答。它帮助了我:)。我在laravel事件文档中搜索此方法,但在那里我找不到,只有手动侦听的方法。