0

hello I've been struggling with this error since yesterday, I need some help here is my middleware and here my route. This page isn’t working localhost redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS.

    public function handle($request, Closure $next)
    {
        if (Auth::check()) {
            $user = Auth::user();
            if ($user->hasAnyRole('school')) {
                return $next($request);
            }
        } else {
            return redirect('login'); 
        }
    }
Route::get('/', 'PagesController@index');
Route::get('/about', 'PagesController@about')->name('about');

Auth::routes();
Route::get('/school', 'HomeController@index')->name('school')->middleware('school');

It's even impossible to access the landing page. Thanks in advance!

Giacomo M
  • 4,450
  • 7
  • 28
  • 57
Ibrahim
  • 55
  • 1
  • 8

2 Answers2

0

You have to use like this

public function __construct(){
    public function handle($request, Closure $next)
        if (Auth::check()) {
            $user = Auth::user();
            if ($user->hasAnyRole('school')) {
                return $next($request);
            }
            else{
                // Another redirect
            }
        } else {
            return redirect()->route('login');
        }
    });
}
A.A Noman
  • 5,244
  • 9
  • 24
  • 46
0

You need to redirect the user again in the else of hasAnyRole function:

public function handle($request, Closure $next)
{
    if (Auth::check()) {
        $user = Auth::user();
        if ($user->hasAnyRole('school')) {
            return $next($request);
        } else {
            // HERE
            return redirect('login'); 
        }
    } else {
        return redirect('login'); 
    }
}
Giacomo M
  • 4,450
  • 7
  • 28
  • 57
  • I tried again to redirect them to the other middleware, and still the same. ``` if (!Auth::check()) { return redirect()->route('login'); } $user = Auth::user(); if($user->hasAnyRole('school')) { return $next($request); } $destinations = ['student','teacher']; foreach($destinations as $destination){ return redirect(route( $user->hasAnyrole($destination))); }``` – Ibrahim Jun 21 '20 at 17:23