一个网站上线,需要分析网站的访问情况,这里就完成一个记录网站访问的日志信息
- 下载包
> composer require jenssegers/agent
- 创建中间件
> php artisan make:middleware Ipmiddleware
打开app\Http\Middleware\Ipmiddleware.php文件
~~~
<?php
namespace App\Http\Middleware;
use App\Models\Ip;
use Closure;
use Jenssegers\Agent\Agent;
class Ipmiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$agent =new Agent();
$task = $agent->platform();
$br =$agent->browser();
$dd = $agent->device();
if ($agent->isPhone()){
$ss ='mobile';
$data['isphone']=1;
}else{
$ss =' ';
}
if ($agent->isRobot()){
$robot = $agent->robot();
$data['isrobot']=1;
}else{
$robot ='';
}
if ($agent->isRobot()) {
}else if ($agent->isPhone()) {
}else{
$data['ispc']=1;
}
$device = $task.'_'.$br.'-'.$dd.'_'.$ss."_".$robot;
$data['url']=$request->url();
$data['ip']=$request->ip();
$data['device']=$device;
Ip::create($data);
return $next($request);
}
}
~~~
- 注册中间件,打开Kernel.php文件
> 'iplog'=>\App\Http\Middleware\Ipmiddleware::class,
- 路由中使用中间件
~~~
//前端
Route::namespace('Home')->middleware('iplog')->group(function (){
Route::get('/','HomeController@index')->name('home.index');//首页
Route::get('category/{category_id}','HomeController@category')->name('home.category');//分类页
Route::get('article/{id}','HomeController@show')->name('home.show');//详细页
});
~~~
访问一篇文章看看是否记录
![](https://img.kancloud.cn/17/4e/174e4fd34f46a6d7da321a21faf38f6f_915x247.png)