Laravel 版本 5.7 -
我目前正在尝试获取登录尝试的次数。 Laravel 的文档没有提供这方面的指南。但我认为通过回溯所有被调用的方法,我越来越接近自己找到答案。
无论如何,我的目标是显示锁定之前的“尝试登录次数/最大登录尝试次数”。
在 Auth\LoginController 中,我可以轻松获取 maxAttempts 的数量,甚至可以设置我首选的最大尝试次数:
protected $maxAttempts = 3;
太棒了。因此,我创建了一个函数来获取登录尝试详细信息:
public function getCurrentAttempts() {
$limiter = $this->limiter();
$login_attempts = array(
// gets the number of current login attempted
'currentAttempts' => $limiter->hit('user'),
// get the number of max attempts allowed
'maxAttempts' => $this->maxAttempts(),
// return 1 or 0 if current login attempts reached max attempts
'locked' => $this->limiter()->tooManyAttempts('user', $this->maxAttempts())
);
return view('auth.login')->withLoginAttempts(
$login_attempts
);
}
请注意:
$this->limiter()->hit(key)
<<< expects a key. I really don't know what kind of key it is expecting. Help anyone? I typed 'user', and for some reason is sending me back the correct number of attempts. But is this correct? Is that the 'key' that $limiter->hit()
正在期待吗? ‘key’不是和Request有关系吗?
其他注意事项: 很好,从 LoginController 我可以通过简单的
$this->maxAttempts()
轻松获取 $maxAttempts 值,这真的很好。但是当前登录尝试的次数又如何呢?把它放在同一个地方不是很理想吗?这就是我想要得到的。
在多次阅读 Laravel 文档后,我开始尝试框架内已内置的各种类,这些类使我能够实现我的目标(获取当前的登录尝试次数)
在LoginController中我们必须
use Illuminate\Http\Request;
,然后通过方法注入,可以在方法中捕获Request $request
。
然后我就能够获得“throttleKey”,这是我需要的密钥,如下所示: 在 LoginController 的方法体中,
$this->limiter()->hit($this->throttleKey($request));
El Sordo 的答案对我有用,但我找到了一种稍微更干净的方法来做到这一点。
首先,在 LoginController 命名空间中使用 RateLimiter:
use Illuminate\Support\Facades\RateLimiter;
然后您可以像这样获取登录尝试次数:
RateLimiter::attempts($this->throttleKey($request))
在我的例子中,我还必须在 LoginController 类中使用 ThrottlesLogins,否则我无法从引用当前类/对象的 $this 调用throttleKey 方法。
use ThrottlesLogins;