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

drewdan's avatar
Level 15

Session or Cookie

Hey Folks,

I have a shopping basket in my application, which I create by creating a UUID, and then storing it on the session, something like:

$request->session()->put('basket', $basketID);

I then store the basket ID in the database, so we can retrieve the items. This approach seems to be working fine.

I've pondered using cookies instead, but found testing them to be a royal pain. But I sort of feel like cookies would be a better option. Does anyone have any experience in this and could point to some pros or cons of the approaches?

Ta Andrew

0 likes
5 replies
Nakov's avatar
Nakov
Best Answer
Level 73

IMO, you could use a cookie as a session driver too, but the cookies are limited to 4kb and you don't know how many items the user will add to the cart + cookies will travel with each request that is being performed on your site. So I would stick to the session.

drewdan's avatar
Level 15

@Nakov thank you for the feedback. Fortunately, in my implementation, the basket items are stored in the DB linked to the basket ID stored in the session, so there is no risk of a cookie growing too large. This allows me visibility over the current baskets and see the conversion of a basket to an order.

Follow-up question, as I said, I store the basket IDs in the DB, and I create a basket in a middleware, which checks to see if a basket exists for the user, and if not, generates one, but I seem to have an insane amount of baskets being generated. Google Analytics suggest I have had 18 unique visitors today yet, I have had 338 basket IDs generated and stored. Everytime I test, I seem to only have the same basket ID, so I don't know where all of these others are being spawned from. Could this be just because people leave, then visit the website again and start a fresh session, or have I just mucked up my implementation somehow?

drewdan's avatar
Level 15

ah, to answer own follow up, it looks like these are crawlers generating the baskets, Googlebot and the like.

Nakov's avatar

@drewdan why not create the basket once the user adds at least one item for buying? Just creating baskets from the middleware does not sound right to me.

1 like
drewdan's avatar
Level 15

@Nakov now you have said it, it seems like the most obvious approach, and I am not sure why I didn't do it before. Amazing :) - thanks for your input, most appreciated!

Please or to participate in this conversation.