Spatie Laravel-activitylog使用Logging模型

时间:2018-01-25 12:22:19

标签: php laravel-5 activitylog spatie

我正在使用this package for activity logging in laravel 我可以从控制器进行日志记录,但我想使用Model。

我从official documentation

中读到了这些有用的信息

但是,它不存储主题id,类型和causer id,类型。我可以将它作为

存储在控制器中
activity()
   ->causedBy($userModel)
   ->performedOn($someContentModel)
   ->log('edited');

如何从模特中做到这一点?建议表示赞赏。

1 个答案:

答案 0 :(得分:1)

好的。现在我得到了你的问题。如果你想在Modal中表现。 以下是我的Business模型类中的示例代码。

 protected static function boot()
    {
        //to log what field update
        static::updating(function ($business) {
            $changes = $business->isDirty() ? $business->getDirty() : false;
            if($changes)
            {
                foreach($changes as $attr => $value)
                {
                    activity()
                        ->performedOn($business)
                        ->causedBy(auth()->user())
                        ->withProperties(['business_name' => $business->name, 'which field updated' => $business->getDirty()])
                        ->log('Business Field <span class="text-green">Updated</span>  - '.$business->name);

                }
            }
        });
    }

对于主题的信息,您必须手动添加,下面是我的示例代码我如何将其存储在控制器中。我希望你能得到一些参考。

activity() 
    ->performedOn($business)
    ->causedBy(auth()->user())
    ->withProperties(['business_name' => $business->name)
    ->log('Business <span class="text-green">Updated</span>  - '.$business->name);

DB记录如下:

db record

+----+----------+-----------------------------------------------------------------+------------+--------------+-----------+-------------+-------------------------------------+---------------------+---------------------+
| id | log_name | description                                                     | subject_id | subject_type | causer_id | causer_type | properties                          | created_at          | updated_at          |
+----+----------+-----------------------------------------------------------------+------------+--------------+-----------+-------------+-------------------------------------+---------------------+---------------------+
|  1 | default  | Business <span class="text-green">Updated</span> - Companies 10 |         10 | App\Business |         1 | App\User    | {"business_name":"Best Restaurant"} | 2017-08-04 14:58:06 | 2017-08-04 14:58:06 |
+----+----------+-----------------------------------------------------------------+------------+--------------+-----------+-------------+-------------------------------------+---------------------+---------------------+