Custom Middleware - Too Many Redirects - Laravel

天大地大妈咪最大 提交于 2021-01-27 07:10:46

问题


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 == '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');
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/47080545/custom-middleware-too-many-redirects-laravel

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