user3718908x100
user3718908x100

Reputation: 8509

Trigger function after session timeout or expire in laravel

I have a question concerning authentication. I have the following function in my authentication controller:

public function signout()
    { 
        // set logged in status to zero in database
        $l = Login::where('user_id', Session::get('user')->user_id)
                ->where('logged_in', 1)->first(); 
        $l->logged_in = 0;
        if ($l->save())
        {
            // log user out
            Auth::logout();
            // Forget user session data
            Session::forget('user');
            // redirect user to login page
            return Redirect::to('/account/signin');
        }
    }

Now in my session config, I have set sessions to expire after 60mins after which the user will obviously be logged out of the system. However that will occur without my other functions executing like setting user logged in status to zero in database or forgetting the user session array. Is there a way I can trigger those functions to execute after login session expire?


I've been looking around again to see if there was already a solution to this. From reading the docs I got excited when i came to the "Events" section because i thought I had found a solution, however I found out later on that there was no such thing as a Session::expire event in laravel, neither is there a function to check whether another user is logged in or not.

Upvotes: 8

Views: 5045

Answers (1)

Alberto
Alberto

Reputation: 878

Your whole premise is wrong: sessions should have an expiry timestamp that's set when user logs in, and updated on every request if you want to have something like "session times out after 1h of inactivity".

Then you can basically:

  1. Check if session is still valid when user performs a request, by checking the timestamp
  2. Delete expired sessions using a scheduled task, so you keep things clean and tidy in the background

Anyway, if for some reason you end up needing to trigger some actions to happen when a user signs out Laravel actually has an Event that's triggered on user logout: 'auth.logout'

Upvotes: 1

Related Questions