laravel middleware error – This page isn’t working 127.0.0.1 redirected you too many times.

I am using a middleware in my project and i created a middle ware file called validlogin.php and i applied middleware for my route which comes after login process and this route called dashboard since then it is showing following error

error – This page isn’t working 127.0.0.1 redirected you too many times.

validlogin.php

public function handle(Request $request, Closure $next)
{
        if(Session()->has('loginid')){
            
            
            return redirect('login');
            
}
return $next($request);
        
}

web.php

Route::get('/add-listing',[front::class,'add_listing'])->name('add-listing')->middleware('valid-login');

kernal.php

'valid-login' => \App\Http\Middleware\validlogin::class,

Answer

You have written you middle ware code in a wrong way, You can use if ...else to check weather it is login or not .In If statement use return $next($request); and in else statement use where you want to redirect the user if he/she is not login into the dashboard. I am writing the correct code below.

if(Session()->has('loginid')){
            
            return $next($request);
            
        }
        else
        {
            return redirect('login');
        }

Leave a Comment