前言
本文主要給大家介紹了關(guān)于laravel模型事件用法的相關(guān)內(nèi)容,文中通過示例代碼介紹了laravel模型事件的多種用法,下面話不多說了,來一起看看詳細(xì)的介紹吧。
用法示例
一 、簡單粗魯(用于本地測試)
路由中定義:
Event::listen('eloquent.updated: App\Post',function (){ dump('測試一下修改事件'); }); Route::post('/post/{id}', 'PostController@update');
二 、生成事件和監(jiān)聽器
在 EventServiceProvider 定義對應(yīng)關(guān)系
protected $listen = [ 'App\Events\PostEvent' => [ 'App\Listeners\PostListener', ], ];
php artisan event:generate //生成文件
event 中注入要操作的類
listen 中handle 方法注入對應(yīng)事件類
public function handle(PostEvent $event) { dump('測試一下修改事件'); }
最后在 post 模型中添加 'events' 屬性
protected $events = [ 'updated' => PostListener::class ];
三 、利用框架的 boot 方法
直接在相關(guān) Model 中定義
public static function boot() { parent::boot(); static::updated(function($model) { dump('測試一下修改事件'); }); }
四 、定義Trait
如果想對多個(gè)模型的updated 或 created 事件進(jìn)行一些操作,該不會(huì)每個(gè)模型都單獨(dú)寫一個(gè)吧.例如: 日志 .
trait LogRecord { //注意,必須以 boot 開頭 public static function bootLogRecord() { foreach(static::getModelEvents() as $event) { static::$event(function ($model){ $model->setRemind(); }); } } public static function getModelEvents() { if(isset(static::$recordEvents)){ return static::$recordEvents; } return ['updated']; } public function setRemind() { dump('記錄邏輯操作'); } }
然后,在模型中use trait 就可以了.
• creating - 對象已經(jīng) ready 但未寫入數(shù)據(jù)庫
• created - 對象已經(jīng)寫入數(shù)據(jù)庫
• updating - 對象已經(jīng)修改但未寫入數(shù)據(jù)庫
• updated - 修改已經(jīng)寫入數(shù)據(jù)庫
• saving - 對象創(chuàng)建或者已更新但未寫入數(shù)據(jù)庫
• saved - 對象創(chuàng)建或者更新已經(jīng)寫入數(shù)據(jù)庫
• deleting - 刪除前
• deleted - 刪除后
• restoring - 恢復(fù)軟刪除前
• restored - 恢復(fù)軟刪除后
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對的支持。