1. 程式人生 > >實現laravel 插入操作日誌到資料庫

實現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,
    ];

大功告成….