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

wisnushin's avatar

Auth::attempt() does not store session without calling redirect()

Hi! I'm currently trying to make custom authentication system for my website and I'm having an issue with how the Auth::attempt() method works.

I have these test codes:

class HomeController extends Controller
{
    
    public function index()
    {
        if (Auth::attempt([
            'email' => '[email protected]',
            'password' => 'testing'
        ])) {
           return redirect('/test'); 
        }

        die;
    }

    public function test()
    {
        dd(Auth::check());
    }
}

Using the example above, when I open index, it redirects to '/test' and Auth::check() returns 'true' correctly.

However if I remove the redirect('/test') line, open index, then manually go to '/test' page it always says false.

It seems like Laravel only stores the session when I call redirect() after attempt(). This, for me, seems like a weird behavior. I was expecting once attempt() is successful Laravel automatically logs the user in and stores the session. Is there any way to achieve the behaviour that I want? ie. store the session without redirect.

Oh, and I'm on Laravel 5.5 on Homestead on Mac OS Sierra.

Thanks!

0 likes
1 reply
Snapey's avatar
Snapey
Best Answer
Level 122

If you 'die' in a script then changes to the session are not yet stored. You have to let the script complete so that the after middleware runs.

Instead of die, return a value, like return ('logged in');

Edited to get my terminology right. Its terminable middleware

https://laravel.com/docs/5.1/middleware#terminable-middleware

1 like

Please or to participate in this conversation.