我正在通过电子邮件验证用户的帐户,我想在帐户验证后将用户直接重定向到主页。
我遇到的问题是我不确定如何使用login
函数实际登录用户。
class VerificationController extends Controller {
public function verify($token){
User::where('email_token',$token)->firstOrFail()->verified();
// auth()->login($user); works if $user exists
return redirect('/home');
}
}
我可以根据email_token
登录用户吗?我试过但它似乎没有按预期工作。
你是正确的方式。你只需要获得User
实例并将其传递给login
类的Auth
方法。我已经为你做了一个示例控制器来展示如何做到这一点。
class VerificationController extends Controller
{
public function verify($token)
{
// Fetch the user by the email token from the database.
// #firstOrFail returns the first matching user or aborts
// the request with a 404 error.
$user = User::where('email_token', $token)->firstOrFail();
// Activate your user or whatever this method does.
$user->verified();
// Logs the Client who did this web request into the
// User account fetched above in.
Auth::login($user);
// Redirect to wherever you want.
return redirect('/home');
}
}
阅读有关在官方文档中验证用户身份的更多信息: https://laravel.com/docs/authentication#other-authentication-methods
首先,您必须在config / auth.php中的providers部分中配置登录模型
在登录模型中也必须进行一些更改
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Authenticatable;
class ModelName extends Model implements \Illuminate\Contracts\Auth\Authenticatable
{
use Authenticatable;
}
并在你的控制器
if (!Auth::attempt(['username' => $username, 'password' => $password])) {
return redirect()->back()->with(['error' => 'Could Not Log You In!']);
} else {
return redirect()->route('routeName');
}
或者您是否要求从控制器手动验证用户,这也是解决方案
Auth::login($user);
其中$ user是相应用户的登录模型记录