Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

johnw65's avatar

Session Timeout - Redirect User to Login

When the session timeout, want to redirect user to login even at ajax request.

If possible, maybe at 2 minute mark, give them a popup to give the user 'session is about to time out... please click here to continue...'

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To redirect the user to the login page when the session times out, you can use Laravel's built-in middleware called AuthenticateSession. This middleware is responsible for verifying that the user's session is still active. If the session has expired, it will redirect the user to the login page.

To display a popup notification to the user before the session times out, you can use JavaScript's setTimeout function to show the popup after a certain amount of time. Here's an example of how you can implement this:

  1. Create a new JavaScript file, let's call it sessionTimeout.js, and place it in your public assets directory.

  2. In the sessionTimeout.js file, add the following code:

setTimeout(function() {
    alert('Session is about to time out... Please click here to continue.');
}, 120000); // 2 minutes in milliseconds
  1. In your main layout file (e.g., app.blade.php), include the sessionTimeout.js file:
<!DOCTYPE html>
<html>
<head>
    <!-- Your head content here -->
    <script src="{{ asset('js/sessionTimeout.js') }}"></script>
</head>
<body>
    <!-- Your body content here -->
</body>
</html>

Now, whenever a user visits your website, the sessionTimeout.js script will start a timer. After 2 minutes (or any other duration you specify), it will display a popup notification to the user.

When the session actually times out, Laravel's AuthenticateSession middleware will automatically redirect the user to the login page, even for AJAX requests.

Note: Make sure you have the necessary JavaScript libraries (e.g., jQuery) included in your layout file if you're using them in your project.

I hope this helps! Let me know if you have any further questions.

Snapey's avatar

@jeffreyway

I hope this helps! Let me know if you have any further questions.

we know Lary has no ears

Please or to participate in this conversation.