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

后端 未结 5 1340
旧时难觅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:10

    If you want to use Query Builder, and Eloquent the only way around this without extending the Core Components (which I don't deem necessary), you can just use the Event System.

    Link: http://laravel.com/docs/events

    So you'd use an event such as user.custom.save, then create a function for use with the query builder which at the end would trigger this event, same as with Eloquent.

    Example:

    class User extends Eloquent
    {
        public function save()
        {
            Event::fire('user.custom.save', array($this));
            parent::save();
        }
    }
    

提交回复
热议问题