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

chrisgrim's avatar

How to use Session correctly

Hi, I am creating a quick voting system for my posts and I have a question about tracking users. I don't want to store their ips in my votes database to ensure they only vote once so I assumed I would use the session. I see that the session "_token": "QFcYtdVv7KcddqB2PHNFp2vcdcp6k6LRTkr2iDS4W", doesn't change unless I load an incognito window. How do I use that token to ensure only one vote per session? It seems like overkill to save that token to a database.

0 likes
4 replies
jlrdw's avatar

You probably need it stored in db. If they logout and re login then they can just vote again.

There are several S.O. articles and some previous Laracasts post that talked about this very same topic.

chrisgrim's avatar

I don't mind if they open an incognito window to vote again, I just want to stop someone clicking over and over again. Also, I am better trying to understand sessions and token. Do you have a link to the other posts?

Snapey's avatar
Snapey
Best Answer
Level 122

Don't check IP address if there is a chance multiple people at the same company might want to vote.

Just write a 'voted' variable into the session and check it each time.

If you don't want it bulletproof, this can be quite simple, but if they vote then they could vote again once the session is renewed.

    if (! session()->has('voted')) {
    
        // not voted. Store the vote

        session(['voted' => true]);
        
    }

You can also use the session()->has('voted') in a blade @if statement to disable the button

jlrdw's avatar

Did not save the links. But for short duration session would work. Session is just a Super Global like post, get.

Except it persist for the duration of the user session unless it times out. When I say short duration, I mean until they logout.

Don't count on cookies neither, though setting a cookie could work, a smart user will just clear all cookies, or login with firefox, and logout then use chrome.

Please or to participate in this conversation.