Laravel 通过中间件 记录操作日志
一、创建操作日志中间件
php artisan make:middleware OperationLog
<?php namespace App\Http\Middleware; use Closure; use PHPUnit\Exception; 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 //判断是后台还是前台用户 if(strpos($path, 'admin/')!==false){ $user_id = isset(auth('web')->user()->id) ?auth('web')->user()->id : 0; $user_name = isset(auth('web')->user()->name) ?auth('web')->user()->name : ''; }else{ $user_id = isset(auth('member')->user()->id) ?auth('member')->user()->id : 0; $user_name = isset(auth('member')->user()->name) ?auth('member')->user()->name : ''; } try{ self::writeLog($user_id,$user_name,$input,$path,$method,$ip); }catch (Exception $e){ echo $e->getMessage(); } return $next($request); } public function writeLog($user_id,$user_name,$input,$path,$method,$ip){ $data = array( 'user_id'=>$user_id, 'user_name'=>$user_name, 'path'=>$path, 'method'=>$method, 'ip'=>$ip, 'input'=>json_encode($input, JSON_UNESCAPED_UNICODE), ); \App\Models\OperationLog::create($data); } }
二、创建表、Model
php artisan make:model Models/OperationLog
三、将中间件注册到Kernel.php 文件
protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, // \Illuminate\Session\Middleware\AuthenticateSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, OperationLog::class, ], 'api' => [ \Barryvdh\Cors\HandleCors::class, 'throttle:600,1', 'bindings', ], ];