激活用户帐户后如何自动登录

时间:2017-09-30 03:31:04

标签: laravel

用户注册我的网站后,系统会向用户随电子邮件和令牌提供的电子邮件发送激活链接。如果电子邮件和令牌与数据库匹配,则应该更新状态。状态已成功更新。我现在想要的是点击链接后自动登录。

下面是检查请求是否有效并且在匹配后应该登录的代码。

http://localhost:8000/verify?email=[email]&token=[token]

控制器

/* GET Method
*/
public function verify(Request $request)
{
    if( $request->email && $request->token )
    {   
        $user = \DB::table('users')
                ->where('email', '=', $request->email)
                ->where('verified_token', '=' , $request->token); 

        //if $user found then automatic login
    }
}

以下是我的User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Model;

class User extends Authenticatable
{
  use Notifiable;
  //more codes below
}

顺便说一句,我正在使用laravel 5.4

4 个答案:

答案 0 :(得分:3)

您可以使用login / loginUsingId方法

手动验证用户身份
public function verify(Request $request)
{
    if( $request->email && $request->token )
    {   
        $user = App\User::where([
                    ['email', '=', $request->email],
                    ['verified_token', '=' , $request->token]
                ])->first();

        //if $user found then automatic login
        if (!empty($user)) {
            $user->update(['status' => 1]); // Change the status
            Auth::loginUsingId($user->id); //login the user using the user id
            redirect('/home'); // redirect the user
        }
    }
}

答案 1 :(得分:1)

在Laravel应用程序中登录的两种方法

1.只是传递用户的对象

 $user = App\User::where([
                ['email', '=', $request->email],
                ['verified_token', '=' , $request->token]
            ])->first();
    if (!empty($user)) {
        $user=$user->update(['status' => 1]); 
        auth()->login($user); 
   }

2)以loginUsingId方式传递用户ID

if (!empty($user)) {
    $user->update(['status' => 1]); 
    auth()->loginUsingId($user); }

答案 2 :(得分:0)

由于您正在检索用户模型,因此您只需使用登录功能:

Auth::login($user);

// Login and "remember" the given user...
Auth::login($user, true);

直接从这里的文档中获取: https://laravel.com/docs/5.4/authentication#other-authentication-methods

答案 3 :(得分:0)

您可以在此部分Auth::login($user)中使用//if $user found then automatic login,您可以visit this link,因为您正在使用 laravel5.4