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条)

报告相同问题?