duanri1985 2018-08-08 09:35
浏览 56
已采纳

Laravel / Eloquent:如何挂钩删除过程?

When a record gets deleted from my_items_table I want to insert the record into my_items_table_archive.

I could do this on each Controller, but would prefer to hook into the Eloquent model.

Is there anything like this?

Pseudocode:

class MyItem extends Model {
    protected function beforeDelete($record) {
        MyItemArchive::create($record); // add record the archive
        return true; // continue deletion of $record 
    }
}

Any idea? Thanks!

  • 写回答

3条回答 默认 最新

  • drcx71276 2018-08-08 09:40
    关注

    Yes, there is something similar to your pseudocode.

    You can utilise Eloquent Events

    A good example of this can be seen below:

    protected $dispatchesEvents = [
        'deleted' => UserDeleted::class,
        'deleting' => UserDeleting::class
    ];
    

    The class in question just needs to adhere to / Follow: Listeners

    You can also use Eloquent Observers / the observer pattern to achieve a similar result.

    Let me know how you get on!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器