根据值Laravel登录用户

问题描述 投票:0回答:2

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

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

php laravel authentication controller
2个回答
1
投票

你是正确的方式。你只需要获得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


1
投票

首先,您必须在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是相应用户的登录模型记录

© www.soinside.com 2019 - 2024. All rights reserved.