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

TwinLight's avatar

Authentication as Guest rather than as logged user

I'm not sure it is appropriate to post long codes here, please check the details in here: http://laravel.io/forum/11-09-2015-login-as-guest-instead-of-user The things is whenever i successfully login, it logged me as a guest rather than as a user. However, when i register it successfully login me as a user. I would like to get some insight on this.

0 likes
17 replies
squigg's avatar

The guest user is a user that is not logged in, so Laravel did not log you in correctly. Really need more detail here, as if you are using the default routes and default login code, and authenticating against email/password then there's not a lot that can go wrong.

Try debug tracing through the method calls where it performs auth->attempt, check what credentials are being sent and compare and what the outcome of that method is. Make sure your login page dumps the $errors so you can see if there are any coming back.

Only thing that jumps out at me is you have added in an attribute setter for the password field. I'm wondering if you are potentially double hashing your password which is then causing the failed logins, as the bcrypt already happens as part of the default Laravel user registration.

1 like
TwinLight's avatar

I just read the doc and there is a rehash function, i will be looking forward to this.

In the mean time, i already tried dd(), var_dump() and mostly it will be null, and false.

And last, dd(Auth::attempt($credentials, $request->has('remember'))) statement at postLogin() it give me "true"

squigg's avatar

If Auth::attempt is returning true then you should be getting logged in correctly. Try dumping Auth::user() immediately after that and do you get a user then?

Maybe it's something to do with your session or cookies that is preventing the login persisting.

1 like
TwinLight's avatar

@squigg , thank you for your reply, please have a look at my codes here: In my AuthenticateUsers.php at this method:

protected function handleUserWasAuthenticated(Request $request, $throttles)
{
    if ($throttles) {
        $this->clearLoginAttempts($request);
    }

    if (method_exists($this, 'authenticated')) {
        return $this->authenticated($request, Auth::user());
    }

    dd(Auth::user(), Auth::Guest());
    return redirect()->intended($this->redirectPath());
}

It still give me an "User object" which is user that successfully login and a "false" from Auth::Guest().

However in my middleware Authenticate.php in handle method:

public function handle($request, Closure $next)
{
    dd(Auth::user(), Auth::Guest());
    if ($this->auth->guest()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('auth/login');
        }
    }
    
    return $next($request);
}

it still giving me "null" and "true". Note that route and kernel still unchanged. This issues same as in here http://laravel.io/forum/03-07-2014-laravel-authentication-issues?page=1#reply-28554

I would like to get some insight about session and cookies which related to authenticate. Thank you

Erik's avatar

Just dd the user object instead of

dd(Auth::user(), Auth::Guest());

dump only

dd(auth()->user());
squigg's avatar

Check using Web Developer tools and ensure that Laravel is correctly setting a session cookie when you are visiting the page. Also try var dumping \Session::all() and look for something relating to login.

Try also setting your own session variable and see if it is persisted across page reloads, as this will confirm whether sessions are working properly.

thomaskim's avatar

Just a note: dd is great for debugging, but it will immediately terminate the script. In order for the user to login properly, you need to let the application terminate on its own so it can properly set the authenticated user's session.

In other words, if you properly logged in but you dd the user, you will see the user on that load. However, on next load, that user is gone because you never let the application properly set the user's session.

2 likes
TwinLight's avatar

@Erik, for dd(auth()->user()); it still give me "null".

@thomaskim, thanks for the advice and to be sure whenever i used dd() i comment it back. But the things is , Auth::Guest will always be true here the snippet. Have a look at bottom.

   public function handle($request, Closure $next)
    {
        //dd(Auth::user(), Auth::Guest());
        //dd(Auth()->user(), Auth::User(), Auth::user(), Auth::Guest());
        if ($this->auth->guest()) {                     //this statement will always be true 
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            } else {
                dd(Auth::user(), Auth::Guest());        //this one will display "null" and "true"
                return redirect()->guest('auth/login');
            }
        }
        
        return $next($request);
    }

@squigg, i just dd(\Session::all()) and i got

    public function handle($request, Closure $next)
    {
        if ($this->auth->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            } else {
                dd(\Session::all());
                return redirect()->guest('auth/login');
            }
        }
        
        return $next($request);
    }

Here is the output

array:6 [▼
  "_token" => "A3Wcph7JYSrhvAJhQN1unZkrO41boQCWcLW4wfSw"
  "url" => []
  "_previous" => array:1 [▶]
  "flash" => array:2 [▶]
  "flash_notification" => []
  "login_82e5d2c56bdd0811318f0cf078b78bfc" => null
]

it look like the login_82e5d2c56bdd0811318f0cf078b78bfc -> is null. Is this the cause of my Auth::Guest() = true ?

Erik's avatar

What does auth()->user() returns after your login method? So like

if(Auth::attempt()) {
    dd(Auth::user());
}
TwinLight's avatar

@Erik, snippet from AuthenticatesUsers.php in postLogin():

    . . . 

        $credentials = $this->getCredentials($request);

        if(Auth::attempt($credentials)) {
            dd(Auth::user());       //it will run this and below is the output
        }

        if (Auth::attempt($credentials, $request->has('remember'))) {       
        dd(Auth::user());                 //if i dd(Auth::user) here, the output will still be the same
            return $this->handleUserWasAuthenticated($request, $throttles);
        }

     . . .

Output

User {#352 ▼
  #fillable: array:7 [▶]
  #table: "Users"
  +timestamps: false
  #primaryKey: "idUsers"
  #hidden: array:2 [▶]
  #connection: null
  #perPage: 15
  +incrementing: true
  #attributes: array:9 [▶]
  #original: array:9 [▼
    "rn" => "1"
    "idusers" => "84"
    "username" => "qweasd"
    "password" => "$2y$10$R.N/3gaNzekLAHSXuH/DgOlVtaDDSWj5iyt1yjT5neTuuZhcZzHoq"
    "email" => "qwe@asd.com"
    "peranan" => "Admin PTJ"
    "status" => "Active"
    "remember_token" => null
    "fk_idstaff" => "1"
  ]
  #relations: []
  #visible: []
  #appends: []
  #guarded: array:1 [▶]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: true
  +wasRecentlyCreated: false
}
TwinLight's avatar

Thing that i don't understand is, whenever it reach the middleware the Auth::guest will be true.

AuthenticateUsers.php in handleUserWasAuthenticated():

    protected function handleUserWasAuthenticated(Request $request, $throttles)
    {
        if ($throttles) {
            $this->clearLoginAttempts($request);
        }

        if (method_exists($this, 'authenticated')) {
            return $this->authenticated($request, Auth::user());
        }

        dd(Auth::user(), Auth::Guest());                
        return redirect()->intended($this->redirectPath());
    }

Output

User {#352 ▼
  #fillable: array:7 [▶]
  #table: "Users"
  +timestamps: false
  #primaryKey: "idUsers"
  #hidden: array:2 [▶]
  #connection: null
  #perPage: 15
  +incrementing: true
  #attributes: array:9 [▶]
  #original: array:9 [▼
    "rn" => "1"
    "idusers" => "84"
    "username" => "qweasd"
    "password" => "$2y$10$R.N/3gaNzekLAHSXuH/DgOlVtaDDSWj5iyt1yjT5neTuuZhcZzHoq"
    "email" => "qwe@asd.com"
    "peranan" => "Admin PTJ"
    "status" => "Active"
    "remember_token" => null
    "fk_idstaff" => "1"
  ]
  #relations: []
  #visible: []
  #appends: []
  #guarded: array:1 [▶]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: true
  +wasRecentlyCreated: false
}

false

Correct me if i'm wrong, so the chronology of login is like this

AuthenticateUsers.php -> Auth::atempt() -> handleUserWasAuthenticated() -> Authenticate.php middleware -> handle() -> $redirectpath -> view.blade.php.

But in my middleware Authenticate.php inside handle() method, if i dd(Auth::guest) will be true. It is not like i don't want to use my middleware, but later in view.blade.php i want to call users name, their email, and etc.

Erik's avatar

It does log you in according to your first output. But do you have two attempts in your postLogin() method?

TwinLight's avatar
TwinLight
OP
Best Answer
Level 1

@Erik , yeah for dd() purpose. But its ok now. This issues can be solve by changing the "users" table primary key. My current PK is "idusers", and because i'm using Laravel's authenticate just rename it to "id". Thanks for helping me.

kenmaclord's avatar

Hello,

sorry to dig this post out, but I face the exact same issue, but the solution you found Erik doesn't work for me because my PK is already id.

Apparently, my credentials are valid and my user is logged in the 'AuthenticatesUsers' trait and the 'handleUserWasAuthenticated' method redirect me correctly. BUT, once I'm back in my routes file, my user is no longer logged in.

@squigg, you talked about session persistence issue, do have any further lead for that ?

Thanks a lot

1 like
wrurik's avatar

@kenmaclord

I had the same problem today. My problem was in the sequence of the middleware. Make sure you load the web-middleware before the auth-middleware

Maybe this will help you too

benitto_raj's avatar

for me . i changed my default guard 'web' to 'api' in config/app.php file . for this reason whenever i attempt to login it return true. but sessions are no longer persisted. just change the default guard to 'web' . it will work. hope this is help for someone. Thank you

Please or to participate in this conversation.