Laravel中的模型事件

人生本无意义,唯有寻趣。
### 一个简单的例子
1
2
3
4
5
6
7
8
9
10
11
12
Event::listen('eloquent.created: App\User', function () {
Log::info('haha');
});

Route::get('hehe', function (){

\App\User::forceCreate([
'name' => 'yangzie',
'email' => 'yang11@qq.ttt',
'password' =>bcrypt(str_random(6))
]);
});
### 比较规整的写法
  • 在Providers\EventServiceProvider.php 添加:

    1
    2
    3
    4
    5
    protected $listen = [
    'App\Events\UserCreated' => [
    'App\Listeners\NotifyAdminUserCreated',
    ],
    ];
  • 执行命令:
    会生成两个文件
    Events/UserCreated.php
    Listeners/NotifyAdminUserCreated.php

    1
    php artisan event:generate
  • 在User 模型中:
    1
    2
    3
    4
    5
    use App\Events\UserCreated;

    protected $events = [
    'created' => UserCreated::class
    ];
  • 在监听文件中
    app\Listeners\NotifyAdminUserCreated.php
    1
    2
    3
    4
    5
    public function handle(UserCreated $event)
    {
    $post = $event->post;
    \Log::info($post);
    }
  • 在事件文件中:
    app\Events\UserCreated.php
    1
    2
    3
    4
    5
    6
    public $post;

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

Observer写法(推荐)

https://laravel-china.org/articles/6657/model-events-and-observer-in-laravel