博主信息
博文 48
粉丝 0
评论 3
访问量 58049
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
Laravel实现将数据库操作记入日志
江流
原创
1672人浏览过

日志数据表迁移文件

  1. <?php
  2. use Illuminate\Database\Migrations\Migration;
  3. use Illuminate\Database\Schema\Blueprint;
  4. use Illuminate\Support\Facades\Schema;
  5. class CreateLogsTable extends Migration
  6. {
  7. /**
  8. * Run the migrations.
  9. *
  10. * @return void
  11. */
  12. public function up()
  13. {
  14. Schema::create('logs', function (Blueprint $table) {
  15. $table->id();
  16. $table->string('username',50)->comment('用户名');
  17. $table->string('query')->comment('SQL语句');
  18. $table->string('para')->comment('参数');
  19. $table->timestamps();
  20. });
  21. }
  22. /**
  23. * Reverse the migrations.
  24. *
  25. * @return void
  26. */
  27. public function down()
  28. {
  29. Schema::dropIfExists('logs');
  30. }
  31. }

Log 模型文件

  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. class Log extends Model
  6. {
  7. use HasFactory;
  8. protected $guarded=[];
  9. }

存入日志记录表

  1. //启用数据操作日志
  2. DB::enableQueryLog();
  3. Book::create(['name'=>'Laravel框架']);
  4. $log['username']="admin";
  5. //(DB::getQueryLog()获取操作日志,是一个二维数组
  6. foreach(DB::getQueryLog() as $operation){
  7. $log['query']=$operation['query'];
  8. $log['para']="";
  9. foreach ($operation['bindings'] as $para){
  10. $log['para'].=$para.",";
  11. }
  12. Log::create($log);
  13. }

以上代码,以使用模型进行数据的添加为例进行说明的,模型的其他操作同样可以写入日志,使用构造查询器也可以将对数据的操作存入日志

本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学