user3095193
user3095193

Reputation: 337

Redirecting middleware route not working in Laravel

I'm trying to create a middleware that if the user has been disabled then they can't access the website. The problem I'm having is that instead of going to the login route it keeps trying to go to the home route.

My middleware

public function handle($request, Closure $next)
{
    if(request()->user()->enabled == true)
    {
        return $next($request);
    }else{
        return redirect()->route('login')->with('error', 'Your account has been disabled.');
    }
}

My home route

Route::get('/home', 'HomeController@index')->name('home')->middleware('enabled');

Upvotes: 0

Views: 211

Answers (1)

Mahmood Ahmad
Mahmood Ahmad

Reputation: 494

In order for the middleware to work as expected you have to logout the user so the middlware will look like below:

public function handle($request, Closure $next)
{
    if(request()->user()->enabled == true)
    {
        return $next($request);
    }else{
        request()->user()->logout() // logout the user
        return redirect()->route('login')->with('error', 'Your account has been disabled.');
    }
}

Upvotes: 1

Related Questions