This article mainly introduces the Laravel framework to implement the operation logging function using middleware. It analyzes the creation and introduction of the Laravel framework middleware and the related implementation techniques of using the middleware for the operation logging function in the form of examples. What is needed Friends can refer to
. This article describes the example of the Laravel framework implementing the operation logging function using middleware. Share it with everyone for your reference, the details are as follows:
Use middleware for operation logging process:
1. Create middleware
php artisan make:middleware AdminOperationLog
2. The file ./app/Http/Middleware/AdminOperationLog.php
is generated. The code is as follows:
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\Http\Models\OperationLog; class AdminOperationLog { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $user_id = 0; if(Auth::check()) { $user_id = (int) Auth::id(); } $_SERVER['admin_uid'] = $user_id; if('GET' != $request->method()){ $input = $request->all(); $log = new OperationLog(); # 提前创建表、model $log->uid = $user_id; $log->path = $request->path(); $log->method = $request->method(); $log->ip = $request->ip(); $log->sql = ''; $log->input = json_encode($input, JSON_UNESCAPED_UNICODE); $log->save(); # 记录日志 } return $next($request); } }
##3. Introduction of middleware ./app/Http/Kernel.php
protected $middlewareGroups = [ 'web' => [ ... \App\Http\Middleware\AdminOperationLog::class, ... ], 'api' => [ 'throttle:60,1', 'bindings', ], ];
Laravel framework implementation utilization The listener performs sql statement recording function
The above is the detailed content of Laravel framework implements operation logging function using middleware. For more information, please follow other related articles on the PHP Chinese website!