我正在尝试记录应用程序的每个请求的数据。如果用户保存特定模型的数据,我会尝试将原始数据保存在与 activity_logs
表关联的 revisions
表中。
我尝试使用模型事件来捕获数据,如下所示:
class BaseModel extends Model
{
public static function boot()
{
parent::boot();
static::saving(function($model){
$revision = new Revision;
$revision->table_name = $model->getTable();
$revision->row_id = $model->id;
$revision->data = json_encode($model->getDirty());
$revision->save();
$log = ActivityLog::find(Session::pull('activity_log_id'));
$log->revision_id = $revision->id;
$log->save();
});
}
}
但是,模型事件似乎是在中间件实例化之前触发的,因此尽管正在保存修订版本,但它是保存在之前的 GET
请求中,而不是新的 中PUT
请求。
activity_logs
的示例如下:
非常感谢任何帮助。
编辑:更新以包含跟踪中间件代码:
public function handle($request, Closure $next)
{
// Handle the next response and check tracking cookie
if($request->hasCookie('session_tracking')) {
$cookie_id = Cookie::get('session_tracking');
$next_request = $next($request);
} else {
$cookie_id = Uuid::generate()->string;
$next_request = $next($request)->withCookie(cookie('session_tracking', $cookie_id));
}
// Get user agent data
$agent = new Agent();
$exception = $next_request->exception;
// Store associated log data
$path = $this->storePaths($request);
$browser = $this->storeBrowser($agent);
$os = $this->storeOS($agent);
$device = $this->storeDevice($agent);
$error = $this->storeError($exception);
// Store the collated log
$activitylog = $this->storeLog($path, $browser, $os, $device, $agent, $request, $cookie_id, $error);
Session::put('activity_log_id', $activitylog->id);
return $next_request;
}
最佳答案
您在创建新的事件日志记录之前正在运行 Controller 。
如果你搬家
$next_request = $next($request);
创建日志记录后,将在执行模型保存方法之前创建新的日志记录。
关于laravel - 在中间件中捕获模型事件 - Laravel 5.4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42959957/