Custom Middleware - Too Many Redirects - Laravel

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

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

A brief explanation.

  • User login → redirected to / home. (Works)
  • If the user is trying to access / admin and their email address is not the same as the one specified in the middleware, redirect to / home.
  • If true, let them in / admin

My middleware is called admin.verify

The routes file is automatically loaded, and if I redirect ('/ home'), it automatically launches my middleware, so I assume that it redirects too often to the main page.

Route 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 == 'Tester@gmail.com') {
        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');
    }
}
+4
source share
1 answer

As discussed in the comments, you have registered this in your global middleware stack, which runs for each individual request. Meaning, you would be constantly redirected to the "home" if you did not fulfill the first condition, because this middleware will run on the "home" (and every other) route. So you go:

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

/Http/Kernel.php :

$middleware, ( )

$middlewareGroup, (web, api ..). , /web.php "-".

$routeMiddleware, , .

+1

Source: https://habr.com/ru/post/1688617/


All Articles