Custom Middleware - Too Many Redirects - Laravel
Asked Answered
C

2

8

I want to create a custom middleware that only if the user is authenticated and the email is a certain email to access the /admin page.

Although, when I specify my custom route and then a redirect it always says too many redirects..

Short Explanation.

  1. User Logs in -> redirected to /home. (Works)
  2. If user tries to access /admin and their email isn't like the one specified in the middleware, redirect to /home.
  3. If its true, let them in /admin

My middleware is called 'admin.verify'

The Routes file is automatically loaded and If I do redirect('/home') it automatically runs my middleware which is why I'm guessing it redirects to homepage too often.

Routes File:

Route::get('/admin', 'AdminController@index')->name('admin.index');

AdminController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AdminController extends Controller
{
    public function __construct(){
      $this->middleware(['auth', 'admin.verify']);
    }


    public function index(){
      return view('admin.test');
    }
}

Middleware:

 public function handle($request, Closure $next)
    {

      if (Auth::check() && Auth::User()->email == '[email protected]') {
        return $next($request);
      } else {
        return redirect()->route('home');
      }

My Home Route:

 GET|HEAD | home | home| App\Http\Controllers\HomeController@index | web,auth

Home Controller:

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('home');
    }
}
Columbia answered 2/11, 2017 at 16:47 Comment(8)
You are redirecting a non-authenticated user to a route which requires authentication. You probably need another case to redirect guests somewhere else.Exquisite
@Exquisite In the AdminController I specify to use the 'auth' middleware. Therefore user must be authenticated.Columbia
In what order is your middleware in the stack in Kernel.php?Sisley
@Devon 'auth' is the first one and the 'admin.verify' is the last oneColumbia
In $routeMiddleware, right? Even so, redirecting to home shouldn't cause an endless loop since home doesn't have this middleware registered.Sisley
Yes, although home controller uses the 'auth' middleware, only authenticated users. I wanted to make a custom middle that only I can access the /admin menu after I am authenticated of course. Except whenever I do return redirect (home) that middleware seems to run even if im not the /home page and says too many redirects.Columbia
Do you mean you get an endless redirect loop on the home route? If that's the case, you probably registered this middleware under the global stack or web stack. You would ONLY want this middleware under the route middleware.Sisley
@Devon THANK YOU!!! IT WORKS. Question though. What happens If I register it under $middleware and $middlewareGroups ('web')?? Because I declared it in there and it automatically ran it.Columbia
S
10

As discussed in the comments, you had registered this under your global middleware stack which runs on every single request. Meaning, you would redirect to 'home' constantly if you failed the first condition because this middleware would be run on the 'home' (and every other) route. So you'd go:

/some/page ... condition failed: redirect 'home'
/home ... condition failed: redirect 'home'
/home ... condition failed: redirect 'home' ... and so on

Inside app/Http/Kernel.php, you have three sections:

$middleware, the global middleware stack (runs on every request)

$middlewareGroup, runs on every request for the group (web, api, etc). Anything in routes/web.php will run through the 'web' group.

$routeMiddleware, route specific middleware which can be enabled on specific routes.

Sisley answered 2/11, 2017 at 17:20 Comment(1)
2 Days of struggling all because I had it on Global! Thank you!Columbia
L
0

If in any case, you encountered this in Laravel 11.

#your middleware class
class EnsureUserIsLogin
{
    function handle(Request $request, Closure $next): Response
    {
        if ($_SERVER['REQUEST_METHOD']!='OPTIONS') {
            if (!Auth::check()) {
                return redirect('/');
            }
        }
        return $next($request);
    }
}

Make sure to exclude the middleware in your target route.

Route::get('/', function () {
    return Inertia::render('Login');
})->withoutMiddleware([EnsureUserIsLogin::class]);
Lamarckism answered 3/8 at 19:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.