Laravel中的模型事件
人生本无意义,唯有寻趣。### 一个简单的例子
1 | Event::listen('eloquent.created: App\User', function () { |
在Providers\EventServiceProvider.php 添加:
1
2
3
4
5protected $listen = [
'App\Events\UserCreated' => [
'App\Listeners\NotifyAdminUserCreated',
],
];执行命令:
会生成两个文件
Events/UserCreated.php
Listeners/NotifyAdminUserCreated.php1
php artisan event:generate
- 在User 模型中:
1
2
3
4
5use App\Events\UserCreated;
protected $events = [
'created' => UserCreated::class
]; - 在监听文件中
app\Listeners\NotifyAdminUserCreated.php1
2
3
4
5public function handle(UserCreated $event)
{
$post = $event->post;
\Log::info($post);
} - 在事件文件中:
app\Events\UserCreated.php1
2
3
4
5
6public $post;
public function __construct($post)
{
$this->post = $post;
}
Observer写法(推荐)
https://laravel-china.org/articles/6657/model-events-and-observer-in-laravel