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

rizwan157's avatar

Laravel 5.6 session persistence issue

I'm getting session persistence issue in laravel 5.6 ... the issue I'm facing is: Like I have 2 users user 1 is logged in from pc 1 and user 2 is logged in from pc 2. Sometimes user 1 gets logged in from user 2 account without logout. Same case with other users like other user and admin.

I've tried to store session in database but again I'm getting this issue again.

PHP version: 7.1 Database: MySQL

I've tried many ways to solve this issue but still getting this issue. Please tell me what to do. I'm really stuck

Thanks, Rizwan

0 likes
19 replies
shez1983's avatar

are you saying TWO diff users get/see each others account?

rizwan157's avatar

Yes, different users are getting other's account without logout .

Yorki's avatar

Do you use custom login method or middleware? I would start from debugging there.

rizwan157's avatar

I'm using builtin login method / middleware.

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/member';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }

    public function logout(Request $request)
    {
        activity('Authentication')
            ->withProperties(['event' => 'logout'])
            ->log(":causer.name logout successfully");

        $this->guard()->logout();

        $request->session()->flush();

        $request->session()->regenerate();

        return redirect('/');
    }

    public function VerifyEmail($EmailVerificationCode)
    {
        $where = [
            'email_verified' => 0,
            'email_verification_code' => $EmailVerificationCode
        ];
        $user = User::where($where)->first();

        if($user != null)
        {
            $user->email_verified = 1;
            $user->save();
            return redirect('login')->with(['message'=>'Email Verified', 'status' => 1]);
        }else{
            return redirect('login')->with(['message' => "You have already verified your email", 'status' => 0]);
        }
    }

    public function login(Request $request)
    {
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }



        if ($this->attemptLogin($request)) {
            // Session::push("user_id", Auth::user()->id);
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);


        activity('Authentication')
            ->withProperties(['event' => 'login'])
            ->log($request->input('username')." attempt to login failed");

        return $this->sendFailedLoginResponse($request);
    }


    /**
     * Validate the user login request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return void
     */
    
    protected function validateLogin(Request $request)
    {
        $this->validate($request, [
            $this->username() => 'required', 'realpassword' => 'required',
        ]);
    }

    /**
     * Attempt to log the user into the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function attemptLogin(Request $request)
    {
        $request['password'] = $request->realpassword;
        return $this->guard()->attempt(
            $this->credentials($request), $request->has('remember')
        );
    }

    /**
     * Get the needed authorization credentials from the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    protected function credentials(Request $request)
    {
        $credentials = $request->only($this->username(), 'realpassword', 'password');
        return $credentials;
    }


    protected function authenticated(Request $request, $user)
    {
        if($user->email_verified != 1)
        {
            Auth::logout();
            return redirect()->back()->withInput()->with('message', 'Please confirm your Email');
        }

        if($user->is_approved != 1)
        {
            Auth::logout();
            return redirect()->back()->withInput()->with('message', 'Admin has not approved your account');
        }

        if($user->status != 1)
        {
            Auth::logout();
            return redirect()->back()->withInput()->with('message', 'Your account is deleted.');
        }

         activity('Authentication')
            ->withProperties(['event' => 'login'])
            ->log(":causer.name logged in successfully");


        if(Auth::user()->hasRole('Admin') || Auth::user()->hasRole('Super-Admin'))
            return redirect()->intended('admin/dashboard');
        else
            return redirect()->intended('employee');
        // elseif($user->roles[0]->name === 'Member')
        //     return redirect()->intended('member');
        
        return redirect()->intended('/');
    }

}

That's login Controller

rizwan157's avatar

@rumm.an I've tried that too. How can we debug, when user 1 is logged in and after sometime it changes to user 2 with all rights of user 2?

On every action log is generated. Even on that log as user 1 was logged in now getting user 2 as currently session has user 2 data.

That's really wired issue I'm facing.

Lukasas's avatar

I'm not completly sure, but you have commented a line in login function

public function login(Request $request)
    {
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }



        if ($this->attemptLogin($request)) {
            // Session::push("user_id", Auth::user()->id);
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);


        activity('Authentication')
            ->withProperties(['event' => 'login'])
            ->log($request->input('username')." attempt to login failed");

        return $this->sendFailedLoginResponse($request);
    }
          // Session::push("user_id", Auth::user()->id);

If I get this right, you've denied recognition of the logged user by removing the only unique value, that can determine which user is logged in.

That would explain why you're user 1 changes into user 2.

rizwan157's avatar

Yes, due to business logic I had to remove the unique constrain from email. This application is for client's office use only, so customers can't access it.

Actually client doesn't have email of all their customers so that's why I had to remove unique constrain from email column.

But I'm using username and password for login not email ID. username is unique

Lukasas's avatar

That doesn't make any sence. It doesn't matter, if it's only for employees or customers. That line of code literally says, that there is a value, that has a Key of "user_id" and value Auth::user()->id. This is key factor of recognizing currently logged user. Otherwise there is no way to determine which user is logged in. This has nothing to do with permissions, this is only for people to log in. If you'd like to restrict access, you'll have to do it somewhere else.

Like I've said, by commenting that line of code, you're denying the system to determine which user detail should be loaded. That's why you're getting this unexpected behavior like after user 1 logs in he gets swapped with user 2. It's simple as that, the last logged in is the one that'll be logged in across all users.

If you're using username as identifier (which I don't recomment) then you should uncomment that line of code and set it to your unique username. Otherwise there will be nothing to recognize correct user.

It would look like this:

Session::push("user_id", Auth::user()->username);

One more think, that line has nothing to do with email. It's unique ID generated by your database which Laravel uses for recognition of user that is trying to log in. Don't misunderstand that with anything else.

rizwan157's avatar

@Lukasas

Session::push("user_id", Auth::user()->id);

Above line of code wasn't written by default in Laravel controller.

I was testing another way to solve this issue. That's why I wrote that line. But that didn't work so I've commented that.

Laravel by default store logged in user data in an object instead of just "Session::push("user_id", Auth::user()->id);"

Lukasas's avatar

Well I'm pretty new to laravel. But anyway, your problem is exactly what I'm saying. The system can't properly recognize currently logged user. It'll work with single user, because there are no other sessions that can interfere with one user, but the problem starts when second user logs in. You need to make sure that there is some identifier for Sessions which can be used to determine which user owns which session.

rizwan157's avatar

@lukasas I'm not using username as identifier and laravel manage sessions out of the box. We don't have to deal with it separately.

rumm.an's avatar

@rizwan157 It would be helpful. If you let us know when does this happen? when a user with id 1 logs in and it becomes the user 2. I mean does is happen on the very next request or on the login request itself?

You said you tried database session. I'll suggest you to post session table contents when this issue happens.

rumm.an's avatar

@rizwan157 I think you have not overriden username method from AuthenticatesUsers trait. If not you should, and return the string (in your case it is 'username') that represents the column that is used to log the user in.

public function username()
{  
    return 'username';
}
rizwan157's avatar

@rumm.an I've overridden username. I haven't touched vendor files. Previously I was getting this error on 5.4 then I have upgraded to 5.6 but still getting same error.

This doesn't happen on every request. It happens like once a day at some random time to random user. That's why I'm stuck here and can't debug.

milosradic's avatar

Did you manage to solve this issue?

I had similar problem. We have micro-caching enabled on server (using this https://engintron.com/).

It cache response to some URL for 1s.

For example: We have two PCs with two different users authenticated. If they hit same GET URL in period less than 1s then second user will get authenticated as first user and will take everything from their session.

After disabling this micro-cache this issue is resolved.

There are other ways without disabling this micro-cache. You can add header Cache-Control: private so you ignore this cache or add URLs which shouldn't be cached. (By default this micro-cache will not cache URLs that match WordPress (/wp-admin) or Joomla administration (/administrator or /admin i am not sure :D)).

hafizhaleem's avatar

You need to followup the new pattern of laravel. When our team of Phd Dissertation writing services firm. Our team face the same type of problem which you are facing we did one thing to solve that problem by changing patterns of laravel.

renzo197455741's avatar

Hi i have the same issue, can you give me more information on how to disable this micro-cache? should i do it on laravel code? or should i call my hosting landlord to disable it for me, thank you

Please or to participate in this conversation.