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

后端 未结 5 1327
旧时难觅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条回答
  •  萌比男神i
    2020-12-19 07:23

    You must never override the save method to override and add your functionnality.

    You have to use the Model Events functionnality that eloquent provides to do that instead.

    To put it simply, you have to define a saving event for you model to override/set/check data that the model is going to save.

    A simple example to put in a User model class:

    //Executed when loading model
    public static function boot()
    {
         parent::boot();
    
         User::creating(function($user){
             $user->value1 = $user->value2 +1;
         });
    }
    

    More information: http://four.laravel.com/docs/eloquent#model-events

提交回复
热议问题