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

amrsubzero's avatar

Laravel - Using Sessions & Storing session to database

I'm using Laravel 5.5

i want to store the session data to the sessions table in the database & use it.

i changed the session_driver in config\session.php from file to database

'driver' => env('SESSION_DRIVER', 'database'),

and created the sessions table

php artisan session:table

here is my Login Controller :

public function login() {
    // Authenticate the user
    if(!auth()->attempt(request([
        'email', 'password'
    ]), true)) {
        return back()->withErrors(['message' => 'Incorrect email or password']);
    }
    
    // I think i should store the session to database here before returning to home page
    
    // Return home
    return redirect()->home();
}

i want after successful login store the session with it's data to the database (sessions) table and use that session in the project e.g get user_agent, last_activity

How i can achieve something like that?

0 likes
4 replies
amrsubzero's avatar

Thanks for your reply.

I'm not using make:auth i'm using custom (login/register) i created.

if there's a tutorial on working user's sessions with database?

e.g store user's sessions like user_agent, last_activity, etc.

Would be thankful.

faabsen's avatar
faabsen
Best Answer
Level 3

As your using the auth()->attempt(...) helper function, after a successful login the session should be automatically saved to the database. What is not working?

By setting the session driver to database any call to the session (helper) functions should resolve to the corresponding database result. (https://stackoverflow.com/questions/26166662/using-laravels-session-database/26168878#26168878). Maybe this helps you too: https://laracasts.com/discuss/channels/laravel/how-to-store-users-id-in-session-table-laravel-5

In addition, here's an old tutorial about the larval session, auth and cache functionality: https://code.tutsplus.com/tutorials/laravel-unwrapped-session-auth-and-cache--cms-19952.

1 like
amrsubzero's avatar

I forgot to run

php artisan config:cache

after changing file to database in 'driver' => env('SESSION_DRIVER', 'database')

But after doing that, it's now working!

Thanks for the information @faabsen i appreciate your help.

1 like

Please or to participate in this conversation.