jorge_dev96
4 months ago
548
5
Laravel

To many redirects error after adding a custom middleware

Posted 4 months ago by jorge_dev96

Hello, again, I added this middleware to check if the user answered a test

My middleware

public function handle($request, Closure $next)
 {
        if (Auth::user()->test == 0){ // 0 for not answered test, 1 for answered test
            return redirect()->route('home');
            //echo "Lol";
            //echo Auth::user()->test; 
        }
        return $next($request);
 }

but when I login or registered i received a To many Redirects error

I added two middlewares in this controller auth and my custom middleware checktest

<?php

...

class HomeController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('checktest');
    }


    public function index(Request $request)
    {

        $users = User::where('id', '!=', auth()->user()->id)->get();
        return view('home', ['users' => $users]);

    }
}

My kernel.php file

    protected $routeMiddleware = [
        'auth' => \ILink\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \ILink\Http\Middleware\RedirectIfAuthenticated::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'checktest' => \ILink\Http\Middleware\CheckIfUserAnsweredTest::class,

    ];

What can I do ?

Please sign in or create an account to participate in this conversation.