Redirect automatically when user session expires in Laravel 5.5

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-01 01:49:11

As your sessions have a fixed lifetime you can pass that information to the client and give the client responsibility for querying the service to determine session expiry at the time when you expect the session to have expired so that instead of constantly querying your service for their sessions status, they're only querying when it's likely to have expired.

  1. A user makes a request to your website
  2. Middleware generates a timestamp representing the point at which their session will expire and returns it to the client to be stored as a cookie
  3. Javascript runs on the client that retrieves the timestamp of their session expiry from the cookie and then when that timestamp is reached you check if the cookie value has changed, and if not then a request is made to your session status endpoint to confirm their session is no longer active
  4. Your session status endpoint returns either an expired status (which triggers the inactive session behaviour) or it returns a new timestamp which you can then update the cookie with so that the process repeats again when that expiry is reached

Personally I would not recommend automatically redirecting someone to the login form when their session has expired because it means when they have many pages open each page will now be the log in form which is a bad user experience. Many technical users will understand that they can log in on one page and then refresh the others, however many non-technical people won't and they will believe they have to enter their username and password on every single page.

If your application depends on an active session even after page load -- i.e it's a single page application that uses ajax -- then when the session expires you should disable the page with a modal that says "Your session has expired, please log in again to continue using this page" and when they click login you first check if they've got an active session and if not only then do you redirect to the log in form. This means that if they have many tabs open and their session expires, when they return to those tabs and click the "log in" button their page use immediately resumes. This is a much better user experience.

You can use Auth::check()

if(Auth::check()) { 
    //Do anything you want
}
return redirect('/login');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!