在laravel中如果对模型进行操作时,可以使用观察器(Observe)对模型监听,进而触发监听事件,包括creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored事件。例如在删除一个数据后,可以在观察器中deleted事件中删除关联数据

1. 创建观察器

php artisan make:observer KolObserver --model=\App\Models\Kol

1.1 观察器类

<?phpnamespace App\Observers;use App\Models\Kol;class KolObserver
{/*** 在创建完成后调用** @param  \App\Models\Kol  $kol* @return void*/public function created(Kol $kol){//}/*** 在更新完成后调用** @param  \App\Models\Kol  $kol* @return void*/public function updated(Kol $kol){//}/*** 在删除完成后调用** @param  \App\Models\Kol  $kol* @return void*/public function deleted(Kol $kol){//}/*** 在删除完成前调用** @param  \App\Models\Kol  $kol* @return void*/public function deleting(Kol $kol){//}
}

2. 注册观察器

App\Providers\AppServiceProvider文件中注册观察者

<?phpnamespace App\Providers;use App\Models\Kol;
use App\Observers\KolObserver;
use Illuminate\Support\ServiceProvider;class AppServiceProvider extends ServiceProvider
{/*** Register any application services.** @return void*/public function register(){//}/*** Bootstrap any application services.** @return void*/public function boot(){Kol::observe(KolObserver::class);}
}

3. 调用方法

    public function update(array $data): bool{$kol = (new Kol())->find($data['id']);//获取模型return $kol->update($data);//更新模型数据}

以上方法中的update调用Illuminate\Database\Eloquent\Model.phpupdate方法

    public function update(array $attributes = [], array $options = []){if (! $this->exists) {return false;}return $this->fill($attributes)->save($options);}

以上方法调用save方法,save方法中调用performUpdate方法,在执行updated方法后观察器中的updated监听方法。

    protected function performUpdate(Builder $query){// If the updating event returns false, we will cancel the update operation so// developers can hook Validation systems into their models and cancel this// operation if the model does not pass validation. Otherwise, we update.if ($this->fireModelEvent('updating') === false) {return false;}// First we need to create a fresh query instance and touch the creation and// update timestamp on the model which are maintained by us for developer// convenience. Then we will just continue saving the model instances.if ($this->usesTimestamps()) {$this->updateTimestamps();}// Once we have run the update operation, we will fire the "updated" event for// this model instance. This will allow developers to hook into these after// models are updated, giving them a chance to do any special processing.$dirty = $this->getDirty();if (count($dirty) > 0) {$this->setKeysForSaveQuery($query)->update($dirty);$this->syncChanges();$this->fireModelEvent('updated', false);}return true;}

4. 注意事项

一定要使用模型中的方法,才能够被监听到。使用DB或以下方法是不能够被观察器监听到

    Kol::where('id', $data['id'])->update($data);

Laravel Observe观察器使用相关推荐

  1. 一起认识下浏览器的5种观察器

    "图片懒加载",这个词语想必大家再熟悉不过了.传统的实现方法是,监听scroll事件,获取img元素相对于视口的顶点位置el.getBoundingClientRect().top ...

  2. IntersectionObserver(交叉观察器)

    文章目录 1.IntersectionObserver 1.1 observe 方法 1.2 unobserve 方法 1.3 disconnect 方法 1.4 takeRecords 方法 1.5 ...

  3. Altium Designer关闭板观察器,放大镜

    左上角的就是板观察器,"Shift+H"就可以关闭,再按一次又打开. "Shift+M"打开这个放大镜,再按一次关闭.

  4. OpenCASCADE绘制测试线束:图形命令之Axonometric观察器

    OpenCASCADE绘制测试线束:图形命令之Axonometric观察器 view, delete axo, pers, top, ... mu, md, 2dmu, 2dmd, zoom, 2dz ...

  5. Laravel服务提供器

    服务提供器是所有 Laravel 应用程序引导中心.你的应用程序自定义的服务.第三方资源包提供的服务以及 Laravel 的所有核心服务都是通过服务提供器进行注册(register)和引导(boot) ...

  6. 使用层级观察器hierarchyviewer综合各种布局实现Android QQ2012登陆界面和注册界面...

    最近工作比较轻松,项目不忙,所以闲着的时间去研究了自己比较感兴趣的UI界面,确实漂亮的UI能给用户带来良好的体验,在android应用中一直尤为重要,这次模仿的是QQ2012Android版的的最新登 ...

  7. unordered_map学习之查找操作和观察器操作count,find, contains(C++20),equal_range,hash_function, key_eq

    本篇学习unordered_map的查找操作和观察器相关的操作,具体的函数如下: count (C++11) 返回匹配特定键的元素数量 (公开成员函数) find (C++11) 寻找带有特定键的元素 ...

  8. LEADTOOLS 入门教程: 使用文件观察器转换文件 - C# .NET Core

    LEADTOOLS 是一个综合工具包的集合,用于将识别.文档.医疗.成像和多媒体技术整合到桌面.服务器.平板电脑.网络和移动解决方案中,是一项企业级文档自动化解决方案,有捕捉,OCR,OMR,表单识别 ...

  9. unordered_multimap学习之查找操作和观察器操作count,find, contains(C++20),equal_range,hash_function, key_eq

    本篇学习unordered_multimap的查找操作和观察器操作,具体函数如下: count (C++11) 返回匹配特定键的元素数量 (公开成员函数) find (C++11) 寻找带有特定键的元 ...

最新文章

  1. ASP.NET中常用的文件上传下载方法
  2. enscape助手_SDT Enscape助手
  3. abap 字符串处理
  4. pythonweb啥意思_python-web-guide
  5. Volley 源码解析之网络请求
  6. C++学习笔记——虚函数
  7. SAP License:再论分摊与分配(含实例)
  8. 计算机通信网络面试题,【算法通信面试题】面试问题:计算机网络(七… - 看准网...
  9. date日期 和 date时间拼接_函数周期表丨时间丨值丨DATE
  10. 0108--/** * 根据最大尺寸和字体计算文字的实际尺寸 */
  11. hnu2021小学期程序设计 棋盘
  12. Linux下DNS服务管理
  13. mybatis配置log4j控制台打印SQL语句
  14. x80hd装linux,台电X80HD:双系统切换的方法演示_台电 X80HD_平板电脑评测-中关村在线...
  15. python寻找完全平方数_279 完全平方数(bfs)
  16. w ndows10启动黑屏,win10开机一直黑屏的解决方法
  17. selenium2 WebDriver 在asp.net项目中的应用
  18. Django用户认证系统
  19. 棋盘覆盖问题与可视化代码演示
  20. torchsummary的用法

热门文章

  1. 谈谈从Windows 和 Unix 的发展看待现代操作系统的跌宕起伏
  2. android 7.0APN信息加载设置流程
  3. 机器学习算法:18大数据挖掘的经典算法以及代码Java实现
  4. 科技大佬走进直播间秀的是什么?苏宁真是6得不行!
  5. Markdown+Typora使用教程
  6. 超省流量的手机浏览器,多御安全浏览器手机版上线了
  7. 【AI 工具】文心一言内测记录
  8. gff文件_GFF格式说明 | Public Library of Bioinformatics
  9. list的分批处理实现的几种方式
  10. 一种智能乒乓球训练系统