当前位置:首页 > CMS教程 > 其它CMS > 列表

实现laravel 插入操作日志到数据库的方法

发布:smiling 来源: PHP粉丝网  添加日期:2022-01-01 21:57:50 浏览: 评论:0 

今天小编就为大家分享一篇实现laravel 插入操作日志到数据库的方法,具有很好的参考价值,希望对大家有所帮助,一起跟随小编过来看看吧。

1 . 创建一个中间件

执行: php artisan make:middleware OperationLog

2 . 在中间件中编写一个writeLog() 或者直接写在handle里面

  1. <?php 
  2.  
  3. namespace App\Http\Middleware; 
  4.  
  5. use App\User; 
  6. use Closure; 
  7. use Illuminate\Support\Facades\Auth; 
  8.  
  9. class OperationLog 
  10. { 
  11.   /** 
  12.    * Handle an incoming request. 
  13.    * 
  14.    * @param \Illuminate\Http\Request $request 
  15.    * @param \Closure $next 
  16.    * @return mixed 
  17.    */ 
  18.   public function handle($request, Closure $next) 
  19.   { 
  20.     $input = $request->all(); //操作的内容 
  21.     $path = $request->path(); //操作的路由 
  22.     $method = $request->method(); //操作的方法 
  23.     $ip = $request->ip(); //操作的IP 
  24.     $usernum = $request->usernum; //操作人(要自己获取) 
  25.     self::writeLog($usernum,$input,$path,$method,$ip); 
  26.  
  27.     return $next($request); 
  28.   } 
  29.   public function writeLog($usernum,$input,$path,$method,$ip){ 
  30.  
  31.     $user = User::where('usernum',$usernum)->first(); 
  32.  
  33.     if($user) { 
  34.       $user_id = $user->userid; 
  35.     } 
  36.  
  37.     $log = new \App\Models\OperationLog(); 
  38.     $log->setAttribute('user_id', $user_id); 
  39.     $log->setAttribute('path', $path); 
  40.     $log->setAttribute('method', $method); 
  41.     $log->setAttribute('ip', $ip); 
  42.     $log->setAttribute('input', json_encode($input, JSON_UNESCAPED_UNICODE)); 
  43.     $log->save(); 
  44.   } 
  45. } 

3 .创建一个OperationLog模型(这里我放在Models文件夹下了)

执行 : php artisan make:model Models\OperationLog

  1. <?php 
  2.  
  3. namespace App\Models; 
  4.  
  5. use Illuminate\Database\Eloquent\Model; 
  6.  
  7. class OperationLog extends Model 
  8. { 
  9.  
  10.   //定义表 
  11.   protected $table = "operation_log"; 
  12.  
  13.   //定义主键 
  14.   protected $primaryKey = "id"; 
  15. } 

4 . 将中间件注册到Kernel.php 文件

  1. /** 
  2.  * The application's global HTTP middleware stack. 
  3.  * 
  4.  * 这些中间件是在对应用程序的每次请求中运行的 
  5.  * 
  6.  * @var array 
  7.  */ 
  8. protected $middleware = [ 
  9.     ......., 
  10.     ......., 
  11.     ......., 
  12.     \App\Http\Middleware\OperationLog::class, 
  13.   ]; 

大功告成…

Tags: laravel插入操作日志

分享到: