有没有办法可以操作Laravel 5.2的登录验证,我想改变它,使用'username'而不是'email'并将返回响应更改为JSON响应?
在Laravel 5.0中,我可以这样做。
在路线中,
//authentication routes
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
在AuthController中,
public function postLogin(Request $request)
{
$this->validate($request, [
'username' => 'required',
'password' => 'required',
]);
$credentials = ($request->only('username', 'password'));
if ($this->auth->attempt($credentials)) :
return response()->JSON([ 'success' => true, 'message' => 'Successfully logged in, redirecting...' ]);
else:
return response()->JSON([ 'success' => false, 'message' => 'Invalid username or password!' ]);
endif;
}
请提供任何帮助,想法,线索,建议和建议吗?
答案 0 :(得分:1)
您只需要更改凭证数组:
$credentials = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
,在你的情况下:
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required',
]);
$credentials = ($request->only('email', 'password'));
if ($this->auth->attempt($credentials)) :
return response()->JSON([ 'success' => true, 'message' => 'Successfully logged in, redirecting...' ]);
else:
return response()->JSON([ 'success' => false, 'message' => 'Invalid username or password!' ]);
endif;
}
希望它有所帮助!
答案 1 :(得分:1)
Laravel 5.2在AuthenticatesUsers特性中附带了一些功能(参见vendor / laravel / framework / src / Illuminate / Foundation / Auth / AuthenticatesUsers.php)。您需要做的就是将以下内容添加到AuthController中。
// Change the field we grab the username/email from
public function loginUsername()
{
return 'username';
}
// If the login is successful, send this as the response
protected function handleUserWasAuthenticated(Request $request, $throttles)
{
return response()->JSON([ 'success' => true, 'message' => 'Successfully logged in, redirecting...' ]);
}
// If the login fails, return this as the response
protected function sendFailedLoginResponse(Request $request)
{
return response()->JSON([ 'success' => false, 'message' => 'Invalid username or password!' ]);
}
所有功能都在AuthenticatesUsers.php中列出。希望这有帮助!
编辑:如下所述,您需要将请求外观添加到控制器:
use Illuminate\Http\Request;