Laravel通过中间件、模型观察者或事件系统实现用户操作日志记录。首先使用中间件捕获POST、PUT、DELETE等请求,将用户IP、URL、输入数据等写入activity_logs表;其次利用模型观察者监听如Article的创建、更新、删除操作,记录具体数据变更;再结合自定义事件与监听器实现逻辑解耦,便于扩展与通知。日志表需包含user_id、ip、url、method、action、model等字段,并建立索引提升查询性能。核心是根据场景选择合适方式并避免记录敏感信息。

Laravel 实现用户操作日志记录,核心思路是捕获用户的请求行为并将其存储到数据库中。可以通过中间件、事件系统或模型观察者来实现,适用于后台管理、权限审计等场景。以下介绍几种实用且易于维护的实现方式。
中间件是记录用户操作最直接的方式,适合记录 HTTP 请求级别的行为,如访问了哪个路由、执行了什么操作。
创建一个日志中间件:
php artisan make:middleware LogUserActivity
在生成的中间件中添加记录逻辑:
app/Http/Middleware/LogUserActivity.php
public function handle($request, \Closure $next)
{
    $response = $next($request);
    // 只记录 POST、PUT、DELETE 等修改类请求
    if (in_array($request->method(), ['POST', 'PUT', 'DELETE'])) {
        \App\Models\ActivityLog::create([
            'user_id'     => auth()->id(),
            'ip_address'  => $request->ip(),
            'url'         => $request->fullUrl(),
            'method'      => $request->method(),
            'user_agent'  => $request->userAgent(),
            'input_data'  => json_encode($request->except(['password', 'password_confirmation'])),
            'status_code' => $response->getStatusCode(),
        ]);
    }
    return $response;
}
将中间件注册到 app/Http/Kernel.php 并应用到需要监控的路由组(如后台)。
如果需要记录具体的数据变化(如某条文章被修改),可以使用 Laravel 的模型观察者。
先创建模型和迁移:
php artisan make:model ActivityLog -m php artisan make:observer ArticleObserver --model=Article </font>
在观察者中记录操作:
class ArticleObserver
{
    public function created($article)
    {
        $this->log('created', $article);
    }
    public function updated($article)
    {
        $this->log('updated', $article);
    }
    public function deleted($article)
    {
        $this->log('deleted', $article);
    }
    private function log($action, $model)
    {
        ActivityLog::create([
            'user_id' => auth()->id(),
            'action'  => $action,
            'model'   => get_class($model),
            'model_id'=> $model->id,
            'data'    => $model->toJson(),
        ]);
    }
}
在 AppServiceProvider 中注册观察者:
Article::observe(ArticleObserver::class);
更灵活的方式是定义自定义事件和监听器,便于扩展和测试。
生成事件和监听器:
php artisan make:event UserActionLogged php artisan make:listener SendLogNotification --queue
触发事件的地方(例如控制器中):
event(new UserActionLogged(auth()->user(), 'exported report', $request->ip()));
监听器中可写入数据库或发送通知,实现逻辑分离。
创建 activity_logs 表用于存储记录:
Schema::create('activity_logs', function ($table) {
    $table->id();
    $table->unsignedBigInteger('user_id')->nullable();
    $table->string('ip_address', 45)->nullable();
    $table->text('url')->nullable();
    $table->string('method')->nullable();
    $table->text('user_agent')->nullable();
    $table->text('input_data')->nullable();
    $table->integer('status_code')->nullable();
    $table->string('action')->nullable(); // 如 created, updated
    $table->string('model')->nullable();
    $table->unsignedBigInteger('model_id')->nullable();
    $table->json('data')->nullable();
    $table->timestamps();
    $table->index('user_id');
    $table->index('model');
    $table->index('model_id');
});
基本上就这些。根据项目复杂度选择合适的方式:中间件适合全局请求记录,观察者适合细粒度数据变更,事件系统适合高扩展性设计。关键是避免记录敏感信息(如密码),并合理索引数据库以提升查询效率。
以上就是laravel如何实现用户操作日志记录_Laravel用户操作日志记录方法的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                 
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                            Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号