Browser shows me too many redirects when I use back() helper method.
I have seen many solutions but no one is provided clear solution.
Here is my code.
authentication middleware contains….
public function handle($request, Closure $next)
{
if(Auth::check())
{
return $next($request);
}
return back();
}
On kernel.php add this middleware….
protected $routeMiddleware = [
'auth' => IlluminateAuthMiddlewareAuthenticate::class,
'auth.basic'=>IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
'bindings'=>IlluminateRoutingMiddlewareSubstituteBindings::class,
'can' => IlluminateAuthMiddlewareAuthorize::class,
'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
'authenticate' => AppHttpMiddlewareAuthenticationMiddleware::class,
];
A controller called userController uses this middleware in constructor…
public function __construct()
{
$this->middleware('authenticate');
}
Here is routes.php
Route::get('/', 'PostsController@index');
Route::get('/cpanel','UsersController@dashboard');
Route::group(['prefix'=>'cpanel'],function() {
Route::get('/settings','UsersController@settings');
Route::post('/settings','UsersController@storeSettings');
Route::get('/post/create',function() {
return view('posts.newpost');
})->name('createpost');
Route::post('/post/create','PostsController@create');
Route::get('/posts','PostsController@posts');
Route::delete('/post/delete/{id}','PostsController@delete');
});
And finally postsController method…
public function index()
{
$posts = Post::all();
return view('index',['posts'=>$posts]);
}
But when I type domain/cpanel it shows redirects too many times. I don’t understand why.
2
Answers
your authenticate middleware cause a loop in some situation like there’s no previous visit. Instead, you can for example change
return back();
toreturn redirect()->url('/')
or ignore some method when applying middleware in __constructor()and if you forget, there is auth middleware.
If you do want to redirect in some cases and prevent redirects too many time from the back method, you can do this: