Laravel 5.2 middleware auth keeps redirecting me to login page

Viewed 1249

I'm trying to build a simple admin dashboard with Laravel 5.2 and I created an admin middleware that includes 'web' and 'auth' middleware.

In my kernel.php file:

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

    'api' => [
        'throttle:60,1',
    ],
    'admin' => [
        'web',
        'auth',
    ]
];

In my routes I created a group for my admin routes. Here's the code:

Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function({
    Route::get('/', [
        'as'   => 'admin',
        'middleware' => 'admin', 
        'uses' => 'LoginController@dashboard',
    ]);

    Route::get('/login', [
        'as'   => 'login',
        'uses' => 'LoginController@login'
    ]);

    Route::post('/login', [
        'as'   => 'post_login',
        'uses' => 'LoginController@authenticate'
    ]);

});

The LoginController:

class LoginController extends Controller
{
    public function dashboard()
    {
        return 'hey';
    }
    public function login()
    {   
        return view('admin.login');
    }
    public function authenticate()
    {   
         $requestData = request()->all();
         $email = $requestData['email'];
         $password = $requestData['password'];

         if (Auth::attempt(['email' => $email, 'password' => $password])) {

            return redirect()->intended('admin');
         }
    } 
}

And the middleware:

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->guest()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('admin/login');
        }
    }
    return $next($request);
}

Now, the problem, is that if add my 'admin' middleware to the route group I get the 'too many redirects loop' and if I use it only on the admin root route like in the code that shown I'm always redirected to the login view. I'm always passing through the middleware even after authenticating the user. For what I understood from the documentation, after the user credentials check I should get redirected to the url I was trying to access in the first place without passing again through the middleware.

Can someone please tell me what am I missing?

Thanks in advance!

0 Answers
Related