编辑 - 添加附加身份验证详细信息
在 Laravel 中设置记住我
- 迁移(创建)用户表时添加 $table->rememberToken()
在您的用户表中创建该列。
- 当用户注册您的服务时,添加一个复选框以允许他们
做出决定,或者如果您不提供,您可以将其设置为真
用户选择步骤 3 中描述的选项
< input type="checkbox" name="remember" >
-
在您的控制器中添加以下代码:
if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) {
// The user is being remembered...
}
Users 表必须包含每 1. 的字符串 remember_token 列,现在假设您已将令牌列添加到 User 表中,您可以将布尔值作为第二个参数传递给尝试方法,这将使用户无限期地通过身份验证,或直到他们手动注销。即 Auth::attempt([$creditentials], true);
旁注:the Illuminate\Contracts\Auth\UserProvider 合约,公共函数updateRememberToken(Authenticatable $user, $token) 使用存储在 User 表中的用户 UID 和令牌来存储会话身份验证。
验证一次:
Laravel 有一个方法可以将用户登录到应用程序以获取单个请求。没有会话或 cookie。与无状态 API 一起使用。
if (Auth::once($credentials)) {
//
}
其他说明
当用户注销时,记住 cookie 不会自动取消设置。但是,使用我在下面的 cookie 示例中解释的 cookie,您可以在注销后返回重定向响应之前将其添加到控制器中的注销函数中。
public function logout() {
// your logout code e.g. notfications, DB updates, etc
// Get remember_me cookie name
$rememberCookie = Auth::getRecallerName();
// Forget the cookie
$forgetCookie = Cookie::forget($rememberCookie);
// return response (in the case of json / JS) or redirect below will work
return Redirect::to('/')->withCookie($forgetCookie);
OR you could q$ueue it up for later if you are elsewhere and cannot return a response immediately
Cookie::queue(forgetCookie);
}
可能对您有所帮助的基本通用 cookie 示例。使用 Laravel 服务提供者有更好的方法来做到这一点
// cookie key
private $myCookieKey = 'myAppCookie';
// example of cookie value but can be any string
private $cookieValue = 'myCompany';
// inside of a controller or a protected abstract class in Controller,
// or setup in a service ... etc.
protected function cookieExample(Request $request)
{
// return true if cookie key
if ($request->has($this->myCookieKey)) {
$valueInsideOfCookie = Cookie::get($this->myCookieKey);
// do something with $valueInsideOfCookie
} else {
// queue a cookie with the next response
Cookie::queue($this->myCookieKey, $this->cookieValue);
}
}
public function exampleControllerFunction(Request $request)
{
$this->cookieExample($request);
// rest of function one code
}
public function secondControllerFunction(Request $request)
{
$this->cookieExample($request);
// rest of function two code
}