Laravel 5.3 Auth:attempt is not working

谁都会走 提交于 2019-12-13 06:46:11

问题


Dont matter if i insert valid or invalid credentials, the user is always redirect to the route defined in RedirectIfAuthenticated middleware. My question: How can i redirect authenticated users to different route than non authenticated user?

RedirectIfAuthenticated (Middleware):

public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            return redirect('/');
        }

        return $next($request);

This is my LoginController:

   public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }

public function authenticate(Request $data){
    if (Auth::attempt( ['cnpj' => $data['cnpj'], 'password' => $data['password'] ] )){
        return redirect()->route('someroute');
    }
    else{
        return redirect()->route('login');

    }

Routes:

Route::get('/', function () {
    return view('welcome');
}) -> name('/');

Route::post('/register', 'Auth\RegisterController@create');

Route::get('/register', function () {
    return view('auth.register');
});

Route::get('/login', function (){
    return view('auth.login');
})->name('login');

Route::post('/login', 'Auth\LoginController@authenticate');

回答1:


In your LoginController, you have set the guest middleware to apply to all routes except for logout. That means that a user who is authenticated can never get to the authenticate method because the middleware has already been run and has redirected the user.

The simplest fix would be to add the authenticate method to the exclusions for the guest middleware:

public function __construct()
{
    $this->middleware('guest', ['except' => ['logout', 'authenticate']]);
}

It appears from your question that you don't really understand Laravel's concepts of Middleware, Routing, and Authentication. I highly recommend that you reread the documentation on those features, because it looks like you are trying to manually implement features that already exist in the framework.



来源:https://stackoverflow.com/questions/39451427/laravel-5-3-authattempt-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!