透過觀察者監聽模型事件

helong3314發表於2021-07-14

預設生成的 UserObserver 會為 createdupdateddeletedrestoredforceDeleted(強制刪除) 事件定義一個空方法

php artisan make:observe UserObserver --model=User
<?php

namespace App\Observers;

use Modules\Auth\Entities\User;

class UserObserver
{
  /**
 * Handle the User "created" event. * * @param \Modules\Auth\Entities\User $user
  * @return void
 */  public function created(User $user)
 {  //
  }

  /**
 * Handle the User "updated" event. * * @param \Modules\Auth\Entities\User $user
  * @return void
 */  public function updated(User $user)
 {  //
  }

  /**
 * Handle the User "deleted" event. * * @param \Modules\Auth\Entities\User $user
  * @return void
 */  public function deleted(User $user)
 {  //
  }

  /**
 * Handle the User "restored" event. * * @param \Modules\Auth\Entities\User $user
  * @return void
 */  public function restored(User $user)
 {  //
  }

  /**
 * Handle the User "force deleted" event. * * @param \Modules\Auth\Entities\User $user
  * @return void
 */  public function forceDeleted(User $user)
 {  //
  }
}

你可以把前面定義的 retriveddeletingdeleted 事件監聽程式碼遷移過來,也可以將不需監聽的事件方法移除,這裡我們將編寫儲存模型時涉及的模型事件,包括 savingcreatingupdatingupdatedcreated

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章