Laravel 观察者不工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48564400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
laravel observers are not working
提问by wahdan
I am trying to listen to model events using laravel observers.The problem is when i submit my form (update or creating new records), nothing happened at all .Do i miss something ?
我正在尝试使用laravel 观察者监听模型事件。问题是当我提交表单(更新或创建新记录)时,什么也没发生。我错过了什么吗?
app.php
应用程序.php
'providers' => [
...
App\Providers\CasesManagerServiceProvider::class,
]
CasesManagerServiceProvider.php
CasesManagerServiceProvider.php
class CasesManagerServiceProvider extends ServiceProvider
{
public function boot( )
{
Cases::observe(CasesObserver::class);
}
public function register()
{
}
}
CasesObserver.php
案例观察者.php
class CasesObserver
{
private $cases;
public function __construct(Cases $cases){
$this->cases = $cases;
}
public function creating(Cases $case)
{
dd('creating');
}
public function saved(Cases $case)
{
dd('saved');
}
public function updating($case)
{
dd('updating');
}
public function updated($case)
{
dd('updated');
}
}
Cases.php
案例.php
class Cases extends Model
{
const UPDATED_AT = 'modified_at';
protected $dispatchesEvents = [
'updating' => CasesObserver::class,
'updated' => CasesObserver::class,
'creating' => CasesObserver::class,
'saved' => CasesObserver::class,
];
}
采纳答案by wahdan
Ok i have found my answer . All the problem was when I added
use app\Observers\CasesObserver;
in CasesManagerServiceProvider.php
instead of use App\Observers\CasesObserver;
.
Yes the Camel case of App
was the problem, so i changed to App and all things are working fine now.
好的,我找到了我的答案。所有的问题是,当我加入
use app\Observers\CasesObserver;
的CasesManagerServiceProvider.php
,而不是use App\Observers\CasesObserver;
。是的,Camel caseApp
是问题所在,所以我改用 App,现在一切正常。
回答by Ali
for me, the problem was registering observer in the register() method!
so when I put it in the boot() method
every thing worked well! the reason is the order of running methods in service providers which are mentioned hear
对我来说,问题是在中注册观察者,register() method!
所以当我把它放进去时,boot() method
一切都很好!原因是提到的服务提供者中运行方法的顺序听到
hope be useful
希望有用
回答by Nikita
You do not need to use $dispatchesEvents in your case. You should try to remove $dispatchesEvents from model, and remove __constructor() from CasesObserver.
您不需要在您的情况下使用 $dispatchesEvents 。您应该尝试从模型中删除 $dispatchesEvents,并从 CasesObserver 中删除 __constructor()。
回答by Gilberto Albino
It seems to be a misuse of Composer and Laravel themselves.
这似乎是对 Composer 和 Laravel 本身的滥用。
You should inform them that you have added some files and configurations:
你应该通知他们你已经添加了一些文件和配置:
To autoload the files:
要自动加载文件:
composer dump
To reconfigure the cache:
要重新配置缓存:
php artisan config:cache
Hope this help you too!
希望这对你也有帮助!