How to logout and redirect to login page using Laravel 5.4?

前端 未结 11 1884
天命终不由人
天命终不由人 2020-12-23 08:58

I am using Laravel 5.4 and trying to implement authentication system. I used php artisan command make:auth to setup it. I edited the views according to my layout. Now, when

相关标签:
11条回答
  • 2020-12-23 09:30

    I recommend you stick with Laravel auth routes in web.php: Auth::routes()

    It will create the following route:

    POST | logout | App\Http\Controllers\Auth\LoginController@logout
    

    You will need to logout using a POST form. This way you will also need the CSRF token which is recommended.

    <form method="POST" action="{{ route('logout') }}">
      @csrf
      <button type="submit">Logout</button>
    </form>
    
    0 讨论(0)
  • 2020-12-23 09:32

    You can use the following in your controller:

    return redirect('login')->with(Auth::logout());
    
    0 讨论(0)
  • 2020-12-23 09:32

    It's better and safer to add to your LoginController.php the following code, that runs only after the standard logout:

    use AuthenticatesUsers;
    
    protected function loggedOut(Request $request)
        {
            return redirect('/new/redirect/you/want');
        }
    
    0 讨论(0)
  • 2020-12-23 09:34

    In 5.5

    adding

    Route::get('logout', 'Auth\LoginController@logout');

    to my routes file works fine.

    0 讨论(0)
  • 2020-12-23 09:34

    if you are looking to do it via code on specific conditions, here is the solution worked for me. I have used in middleware to block certain users: these lines from below is the actual code to logout:

    $auth = new LoginController();
    $auth->logout($request);
    

    Complete File:

    namespace App\Http\Middleware;
    use Closure;
    use Auth;
    use App\Http\Controllers\Auth\LoginController;
    class ExcludeCustomers{
        public function handle($request, Closure $next){
            $user = Auth::guard()->user();
            if( $user->role == 3 ) {
                $auth = new LoginController();
                $auth->logout($request);
                header("Location: https://google.com");
                die();
            } 
            return $next($request);
        }
    }
    
    0 讨论(0)
  • 2020-12-23 09:37

    If you used the auth scaffolding in 5.5 simply direct your href to:

    {{ route('logout') }}
    

    There is no need to alter any routes or controllers.

    0 讨论(0)
提交回复
热议问题