How to keep single session per user in Laravel

Standard

By now, most of you know about the PHP framework Laravel. It’s beautiful and those who haven’t tried this yet, please feel free to try it. I’m sure that you will love it. Coming to the requirement, our project required single session per user, meaning a user’s login process would clear all other sessions (or last session to be precise) from other devices or browsers for the same user. After a few study, here’s what I did to resolve it.

Added the following method in LoginController.php

/**
 * Swap a user session with a current one
 * 
 * @param \App\User $user
 * @return boolean
 */
protected function swapUserSession($user)
    {
        if (!($user instanceof \App\User)) {
            return false;
        }

        $new_session_id = Session::getId(); //get new session_id after user sign in
        $last_session = Session::getHandler()->read($user->last_session_id); // retrive last session

        if ($last_session) {
            Session::getHandler()->destroy($user->last_session_id);
        }

        $user->last_session_id = $new_session_id;
        $user->save();

        return true;
    }

Added a column ‘last_session_id’ in users table and in user model, added ‘last_session_id’ in the ‘fillable’ array.

That’s all. If you know any better method to handle this, please feel free to leave a comment.

Thanks for reading this post.

Advertisements

I will be happy to answer your queries

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s