---
# System prepended metadata

title: observers
tags: [需要修正, observer, laravel]

---

# observers

> 監聽 model event 

eloqunet model 有很多事件當這些事件發生時你可以去做相對應的動作

## 參考

https://learnku.com/articles/6657/model-events-and-observer-in-laravel
https://laravel.com/docs/5.5/eloquent#events

## make:observer

5.6 版本以後才有 

php artisan make:observer UserObserver --model=User

https://laravel.com/docs/5.6/eloquent#observers

## 設定監聽


```php=
// AppServiceProvider 

use App\User;
use App\Observers\UserObserver;

public function boot()
{
    User::observe(UserObserver::class);
}


```

## model lifecycle

- retrieved = 存在的 model 從資料庫拿出來後
- creating = 即將建立的事件
- created = 建立後
- updating = 即將更新
- updated = 更新後
- saving = 即將保存
- saved = 保存後
- deleting = 即將刪除
- deleted = 刪除後
- restoring = 即將從軟刪除恢復
- restored = 軟刪除狀態恢復後



###### tags: `laravel` `observer` `需要修正`


{%hackmd BJrTq20hE %}
