类似的问题,但它们似乎都不完整,因为它们指的是不存在的函数。
我指的是:
使用 laravel 检查活动用户状态
仅当用户使用Laravel处于活动状态时才登录
扩展Laravel 5内置身份验证以仅"如果用户==活动"登录
在所有这些中,都有提出的解决方案,主要是从AuthController
改变函数,但是这些函数不存在。
我使用的是最新版本的Laravel(5.2),所以我默认提到的文件看起来像:https://github.com/laravel/laravel/blob/master/app/Http/Controllers/Auth/AuthController.php
现在,如何实现此功能?我尝试将public function postLogin()
(如其他提到的帖子中所建议的那样)复制到该AuthController
文件中。什么都没有改变。
我在这里显然错过了一些东西。
请有人帮忙!
编辑:我添加的功能是:
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
$credentials = $this->getCredentials($request);
// This section is the only change
if (Auth::validate($credentials)) {
$user = Auth::getLastAttempted();
if ($user->active) {
Auth::login($user, $request->has('remember'));
return redirect()->intended($this->redirectPath());
} else {
return redirect($this->loginPath()) // Change this to redirect elsewhere
->withInput($request->only('email', 'remember'))
->withErrors([
'active' => 'You must be active to login.'
]);
}
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
}
AuthController
中的大多数功能都是使用特征添加的。请注意类开头的这一行:
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
如果您查看AuthenticatesAndRegistersUsers,您可以看到它确实具有postLogin方法。
至于为什么实现此方法不起作用:我认为您在方法签名中缺少$request
参数。
如果不是这种情况,请在您的问题中添加更大的代码片段。
编辑:用于将来调试:php artisan route:list
为您提供了哪些路由调用哪些方法的列表。这可以提示要重写的方法。
因此,对于在Laravel 5.2上遇到相同问题的每个人,php artisan make:auth
提供的身份验证。
首先重要的是了解Route::auth();
指向login
功能而不是postLogin
(谢谢@lagbox!
然后,您将必须更新AuthController
:
在文件顶部添加:
use Auth;
use IlluminateHttpRequest;
在use AuthenticatesAndRegistersUsers, ThrottlesLogins;
之后添加:
/**
* Where to redirect users if login is unsuccessufull.
*
* @var string
*/
protected $loginPath = '/login';`
以及更新的login
功能:
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
$credentials = $this->getCredentials($request);
// This section is the only change
if (Auth::validate($credentials)) {
$user = Auth::getLastAttempted();
if ($user->active) {
Auth::login($user, $request->has('remember'));
return redirect()->intended($this->redirectPath());
} else {
return redirect($this->loginPath) // Change this to redirect elsewhere
->withInput($request->only('email', 'remember'))
->withErrors([
'active' => 'You must be active to login.'
]);
}
}
return redirect($this->loginPath)
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
}
然后login.blade.php
应该更新以显示新的错误@if ($errors->has('active'))
谢谢你们的帮助!