Laravel多次路由访问



我想知道Laravel是否有任何路由控制,不是用于身份验证,而是用于计数访问。也就是说,我需要知道我访问这条路由的次数。在Laravel有可能吗?

或者我怎么做呢?有必要存储在我的数据库中吗?

我可以想象有两种方法:将计数器存储在数据库中或使用第三方服务。

在我看来,如果你想跟踪访问,我建议使用像谷歌分析这样的工具,并从不必要的数据库语句中解放你的服务器。

无论如何,如果你仍然想自己做这件事,在数据库中存储一个计数器是一种方法。为此,最好的方法是为路由实现一个中间件。

假设你有这条路由www.mysite.com/my-custom-route定义为

Route::get('/my-custom-route', [MyController::class, 'index']);

你可以创建一个中间件https://laravel.com/docs/9.x/middleware#defining-middleware

<?php

namespace AppHttpMiddleware;

use Closure;

class CountVisits
{
/**
* Handle an incoming request.
*
* @param  IlluminateHttpRequest  $request
* @param  Closure  $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Yout logic here
// Increment counter in your DB using eloquent or raw query

return $next($request);
}
}

最后,在路由中使用中间件,这样每次到达路由时,中间件都会在DB中增加一个计数器

use AppHttpMiddlewareCountVisits;
Route::get('/my-custom-route', [MyController::class, 'index'])->middleware(CountVisits::class);

最新更新