繁体   English   中英

根据值Laravel登录用户

[英]Log in a user based on value Laravel

我正在通过电子邮件验证用户的帐户,我想在验证帐户后将用户直接重定向到首页。

我遇到的问题是我不确定如何使用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登录用户吗? 我试过了,但似乎没有按预期工作。

首先,您必须在config / auth.php的provider部分中配置登录模型。

登录模型也必须进行一些更改

<?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是相应用户的登录模型记录

您的方法正确。 您只需要获取User实例并将其传递给Auth类的login方法。 我为您制作了一个示例控制器,以说明如何实现。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM