Trying to get property ‘headers’ of non-object (middleware role authentication)

i want to make two authentication roles(admin and user). every thing work fine, but for example when i am logged as user and i try to access the admin dashboard i want want redirected to the user dashboard instead cause i must not have access to it as a user… the problem is when i try to access the admin dashboard as a user i get this error : Trying to get property 'headers' of non-object

this my two middlewares…

Admin middleware:

public function handle(Request $request, Closure $next)
{
    if (Auth::check() && Auth::user()->role == 'admin'){
        return $next($request);
    }else{
        redirect()->route('login');
    }
}

User middleware:

public function handle(Request $request, Closure $next)
{
    if (Auth::check() && Auth::user()->role == 'user'){
        return $next($request);
    }else{
        redirect()->route('login');
    }
}

and i did edit the RedirectIfAuthenticated middleware to this.

public function handle(Request $request, Closure $next, ...$guards)
{
    $guards = empty($guards) ? [null] : $guards;

    foreach ($guards as $guard) {
        /*if (Auth::guard($guard)->check()) {
            return redirect(RouteServiceProvider::HOME);
        }*/

        if (Auth::guard($guard)->check() && Auth::user()->role == 'user') {
            return redirect()->route('user.dashboard');
        }
        elseif (Auth::guard($guard)->check() && Auth::user()->role == 'admin'){
            return redirect()->route('admin.dashboard');
        }
    }

    return $next($request);
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

In middleware, it is important to handle all cases and return the redirects accordingly :

return redirect()->route('login');

Method 2

You should return the redirect
Admin middleware:

public function handle(Request $request, Closure $next)
{
    if (Auth::check() && Auth::user()->role == 'admin'){
        return $next($request);
    }else{
        return redirect()->route('login');
    }
}

User middleware:

public function handle(Request $request, Closure $next)
{
    if (Auth::check() && Auth::user()->role == 'user'){
        return $next($request);
    }else{
        return redirect()->route('login');
    }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x