如果未激活用户,如何在Laravel Auth中获取特定错误

时间:2017-07-13 10:46:53

标签: php laravel laravel-5

如果用户表中的激活列在laravel 5.4中为0,我该如何向用户显示错误Your account is not activated yet, please verify your Account

这是我的登录

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

use AuthenticatesUsers;

/**
 * Where to redirect users after login.
 *
 * @var string
 */
protected $redirectTo = '/home';

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('guest')->except('logout');
}

public function username()
{
    return 'username';
}

public function credentials(Request $request)
{
    return [
        'username' => $request->username,
        'password' => $request->password,
        'activated' => 1,
    ];
}

目前,如果用户未激活,则会显示Credentials do not match。我在stackoverflow上创建了一个旧问题,它说覆盖了你的postLogin函数AuthController,但在laravel 5.4中,authcontroller不存在

1 个答案:

答案 0 :(得分:1)

最简单的方法是覆盖用户登录后调用的authenticated()方法,然后检查它是否被激活:

public function credentials(Request $request)
{
    return [
        'username' => $request->username,
        'password' => $request->password,
    ];
}

protected function authenticated(Request $request, $user)
{
    if ( !$user->activated ) {
        auth()->logout();

        return back()->withErrors(['email' => 'Your account is not activated yet, please verify your Account.']);
    }

    return redirect()->intended($this->redirectPath());
}

另请注意,您必须在身份验证中间件中添加类似的$user->activated支票,否则用户将能够通过忘记密码页面登录。