Katherine
Katherine

Reputation: 13

Laravel 5.3 : redirected you too many times error

I am experiencing this error when trying to navigate to "/admin". Other routes such as "/employee" are working fine.

Here are my current web routes

Auth::routes();

/* Voyager Routes */
Route::group(['prefix' => 'admin'], function () {
Voyager::routes();
...
});

/* Badge App Routes - All the dashboard routes for managers, employees and HRs are defined here */
Route::group(['middleware' => 'auth', 'prefix' => 'employee'], function () {
  Route::get('/', 'frontend\DashboardController@index')->name('homepage');
  Route::get('dashboard', 'frontend\DashboardController@index')->name('homepage');
  ...
});

Route::group(['middleware' => 'auth'], function () {
  Route::resource('team-manager', 'frontend\TeamManagerController');

  Route::resource('badges', 'backend\BadgeController');
  Route::get('badges/award/{id?}', 'backend\BadgeController@award');
  Route::post('store_award', 'backend\BadgeController@storeAward')->name('store_award');
});

/* User Redirector - Based on user role */
Route::group(['middleware' => ['redirector']], function () {
    Route::get('/');
    Route::get('login');
});

And here's my middleware redirector

public function handle($request, Closure $next){
    if (!Auth::guest()) {
        $user = User::find(Auth::id());
        // TODO: fix static id below
        return $user->role_id == 1 ? redirect('admin') : redirect('employee');
    }
    return redirect(route('voyager.login'));
}

Thank you in advance!

Upvotes: 1

Views: 1865

Answers (1)

Morteza Rajabi
Morteza Rajabi

Reputation: 2913

The problem is in your middleware:

return $user->role_id == 1 ? redirect('admin') : redirect('employee');

You have admin role, and you are also in /admin page. Then your middleware redirects you again and again to /admin.

It is better to check if the user is not in the /admin or /admin/* related routes, then redirect him to admin.

if($user->role_id == 1) {

    //check if user is in /admin or /admin related routes.
    return ($request->is('/admin') or $request->is('/admin/*')) ? $next($request) : redirect('admin');

} else {
    redirect('/employee');
}

Upvotes: 1

Related Questions