0
votes

I created a simple authentication with Laravel 5.6 I'm trying to redirect a logged-in user to dashboard if they go to the login page and redirect a guest to a login page if they go to the dashboard page.

I'm using laravel default middleware (RedirectIfAuthenticated) :

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            return redirect('/dashboard');
        }

        return $next($request);
    }
}

Here is my route :

Route::group([ 'middleware' => ['guest','auth:lecturer'] ], function(){
    Route::get('/', "ViewCont\Auth\LoginController@login")->name("login");
    Route::post('/login', "FuncCont\Auth\LoginController@login")->name("login_f");
    Route::get('/register', "ViewCont\Auth\LoginController@register")->name("register");
    Route::post('/register', "FuncCont\Auth\LoginController@register")->name("register_f");
});


Route::group([ 'middleware' => ['check.user.session','auth:lecturer'], 'prefix' => 'dashboard'  ], function(){
    Route::get('/', "ViewCont\Admin\DashboardController@index")->name("dashboard");
});

Everything works fine when a logged-in user try to access login page, they redirected to dashboard page. But, when a guest try to access login page, the page is error : The page isn’t redirecting properly

What did I do wrong ?

1
you are using a middleware that redirects someone away if they are authenticated, and a middleware that redirects someone away if they are not authenticated ... and you have different guards in playlagbox
I thought return $next($request) will continue the processAjabkali Maha
why would you ever apply the auth middleware to a login route? you are saying you have to be authenticated to login, but to be authenticated you have to login ...lagbox

1 Answers

0
votes

There should be 2 different middlewares. RedirectIfAuthenticated redirects user authenticated user from login page and Authenticate that redirects not authenticated user to login page.

So it seems like you need to remove 'auth:lecturer' middleware from login page cause it should be accessible for guest.