Laravel 身份验证在 laravel 5.3 中无法正常工作

Posted

技术标签:

【中文标题】Laravel 身份验证在 laravel 5.3 中无法正常工作【英文标题】:Laravel Authentication not working as secifically in laravel 5.3 【发布时间】:2017-05-10 04:29:28 【问题描述】:

我被困在我的项目中。我希望用户可以使用电子邮件或手机号码登录。这工作得很好。但现在我希望只有活动用户才能使用电子邮件或手机号码登录。我的数据库中有一个活动字段,如果用户处于活动状态或用户处于非活动状态,则设置为 1。但不知道如何执行此操作。请大家帮我解决这个问题。我正在使用 laravel 5.3。

我的LoginController 代码是

<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller

    use AuthenticatesUsers;
    protected $redirectTo = '/home';
    public function __construct()
    
        $this->middleware('guest', ['except' => 'logout']);
    
    protected $username = 'email';
    public function loginNameOrEmail(Request $request)
    
        $field = filter_var($request->input('email'), FILTER_VALIDATE_EMAIL) ? 'email' : 'mobile';
        $request->merge([$field => $request->input('email')]);
        $this->username = $field;
        return $this->login($request);    
    
    public function username()
    
        return $this->username;
    
    protected function authenticated($request, $user)
    
        if($user->is_admin == 1) 
            return redirect()->intended('dashboard');
        
        return redirect()->intended('/home');
    

【问题讨论】:

【参考方案1】:

除了用户的电子邮件和密码之外,您还可以向身份验证查询添加额外的条件。例如,我们可以验证用户是否被标记为“活跃”:

if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) 
    // The user is active, not suspended, and exists.

更新

最简单的方法是将credentials 方法重写为:

protected function credentials(Request $request) 

        $request['active'] = 1;
        return $request->only($this->username(), 'password', 'active');

将此方法添加到您的LoginController

Docs

【讨论】:

如果我添加这个,它会给我一个错误,即 LoginController.php 第 47 行中的 FatalErrorException: Class 'App\Http\Controllers\Auth\Auth' not found.@Amit 我怎样才能覆盖login 方法。你能给我举个例子吗? 如果我覆盖它,它会给我错误,我无法使用电子邮件或手机登录 它给了我空白页。如果我在我的LoginController 中添加getCredentials 那么它也会覆盖我的loginNameOrEmail 并且我无法使用电子邮件或手机号码登录 抱歉,在 L53 中该函数已重命名为 credentials。我会尽快更新答案。你是怎么解决的?

以上是关于Laravel 身份验证在 laravel 5.3 中无法正常工作的主要内容,如果未能解决你的问题,请参考以下文章