retrieved, //从数据库中检索现有模型时会触发
creating,
created,
updating,
updated,
saving,
saved,
deleting,
deleted,
restoring, //正在软删除
restored
//app/Providers/EventServiceProvider.php文件在监听属性listen数组中添加要监听的eloquent事件。
protected $listen = [
'App\Events\Event' => [
'App\Listeners\EventListener',
],
'App\Events\UserSaved' => [
'App\Listeners\UserSavedListener',
],
'App\Events\UserDeleting' => [
'App\Listeners\UserDeletingListener',
],
'App\Events\UserDeleted' => [
'App\Listeners\UserDeletedListener',
],
];
2. 使用artisan生成事件和监听器
php artisan event:generate
执行成功后会自动生成EventServiceProvider中listen数组中列出的所有事件和监听器,多次生成,如果已经存在的监听器和事件则保持不变
//事件生成文件
app/Events/UserDeleted.php
app/Events/UserDeleting.php
app/Events/UserSaved.php
//监听器生成文件
app/Listeners/UserDeletedListener.php
app/Listeners/UserDeletingListener.php
app/Listeners/UserSavedListener.php
3. 创建观察者类来监听
观察者类能反射要监听的eloquent事件对应的方法名称,每个方法的参数都必须是这个模型的唯一参数。具体触发事件后要执行的逻辑代码在此处书写
//创建观察类 app/Observers/UserObserver.php
/**
* Created by PhpStorm.
* User: hsingyue
* Date: 2018/9/7
* Time: 16:38
*/
namespace App\Observers;
use App\Model\User;
class UserObserver
{
/**
* 监听用户创建事件.
*
* @param User $user
* @return void
*/
public function created(User $user)
{
dump('添加记录完成');
dump($user->toArray());
}
/**
* 监听用户删除正在事件.
*
* @param User $user
* @return void
*/
public function deleting(User $user)
{
echo "正在删除";
$user->toArray();
}
/**
* 监听用户删除完成事件
*
* @param User $user
* @return void
*/
public function deleted(User $user)
{
echo "删除完成";
$user->toArray();
}
}
4. 注册观察者
在服务提供者的boot方法中注册想要观察模型(User)的Observe方法。
// 在app/Providers/AppServiceProvider.php文件中boot方法中添加
namespace App\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\DB;
//引入模型和观察者
use App\Model\User;
use App\Observers\UserObserver;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//这里注册user观察者
User::observe(UserObserver::class);
}
5. 测试
控制器中添加记录后访问查看效果
public function test()
{
$user = new User;
$user->name = 'xiaoming';
$user->password = 'DF4S5GE52S';
$user->save();
}
控制器中删除记录后访问查看效果
public function test1()
{
$user = new User;
$user::destroy(1);
}