Laravel: performing some task on every insert/update when using Query Builder or Eloquent ORM

后端 未结 5 1323
旧时难觅i
旧时难觅i 2020-12-19 06:32

The Problem

I would like to automatically add created_by and modified_by fields to every insert/update to a database table in Laravel 4,

5条回答
  •  無奈伤痛
    2020-12-19 07:07

    In Laravel 5.3 if you like to call a single method on each save/update from a single point without making any additional changes in each of the extended Models, you can have a custom listener for eloquent events. As documetation says it can be done only for per Model. But creating a custom listener allow to access any event in any Model.

    Just add a listener to boot() method in EventServiceProvider like below and modify accordingly.

    Event::listen(['eloquent.saving: *', 'eloquent.creating: *'], function(){
            //your method content
            //returning false will cancel saving the model
     });
    

    Please note that wildcard used to match any model. See documentation for more on events.

提交回复
热议问题