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

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了实现laravel 插入操作日志到数据库的方法脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

1 . 创建一个中间件

执行: php artisan make:middleware OperationLog

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

<?php

namespace App\Http\Middleware;

use App\User;
use Closure;
use Illuminate\Support\Facades\Auth;

class OperationLog
{
  /**
   * Handle an incoming request.
   *
   * @param \Illuminate\Http\Request $request
   * @param \Closure $next
   * @return mixed
   */
  public function handle($request, Closure $next)
  {
    $input = $request->all(); //操作的内容
    $path = $request->path(); //操作的路由
    $method = $request->method(); //操作的方法
    $ip = $request->ip(); //操作的IP
    $usernum = $request->usernum; //操作人(要自己获取)
    self::writeLog($usernum,$input,$path,$method,$ip);

    return $next($request);
  }
  public function writeLog($usernum,$input,$path,$method,$ip){

    $user = User::where('usernum',$usernum)->first();

    if($user) {
      $user_id = $user->userid;
    }

    $log = new \App\Models\OperationLog();
    $log->setAttribute('user_id', $user_id);
    $log->setAttribute('path', $path);
    $log->setAttribute('method', $method);
    $log->setAttribute('ip', $ip);
    $log->setAttribute('input', json_encode($input, JSON_UNESCAPED_UNICODE));
    $log->save();
  }
}

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

执行 : php artisan make:model Models\OperationLog

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class OperationLog extends Model
{

  //定义表
  protected $table = "operation_log";

  //定义主键
  protected $primaryKey = "id";
}

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

/**
 * The application's global HTTP middleware stack.
 *
 * 这些中间件是在对应用程序的每次请求中运行的
 *
 * @var array
 */
protected $middleware = [
    .......,
    .......,
    .......,
    \App\Http\Middleware\OperationLog::class,
  ];

大功告成…

以上这篇实现laravel 插入操作日志到数据库的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本宝典。

脚本宝典总结

以上是脚本宝典为你收集整理的实现laravel 插入操作日志到数据库的方法全部内容,希望文章能够帮你解决实现laravel 插入操作日志到数据库的方法所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: