Why not just associate each favorite between a product and a user record?
Ideally to favorite any product you would need to be logged into the application.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I am working on a site that another developer started and there is some Vue JS code to "favorite" and "unfavorite" products. He used sessions and stores the session ID and the "favorited" product IDs in a database table. It works great with a single session, but if you close the browser and come back to the site, obviously the session is gone and you can't see your "favorited" products any more.
I want to use a cookie to track users so when they come back it can look up their data in the database and create a new session with their previously saved favorites. However, I am not entirely sure how to do this. I have seen answers all over the place and all of them are using the cookie itself to store the session data. I just want to use the cookie to store some long ID (maybe a 32 character random string) and then I can store this in the database. I am not sure what the best approach is for this.
Here is the code that sets and gets the session data:
public function favoriteProduct(Request $request, $productId) {
if ((int) $productId > 0) {
$productFavorite = new productFavorite;
$productFavorite->session_id = session()->getId();
$productFavorite->product_id = $productId;
$productFavorite->created_at = now();
$productFavorite->save();
// Send back an array of favorite products
return ProductFavorite::where('session_id', session()->getId())->
get()->
map(function ($productFavorite) {
return $productFavorite->product_id;
});
}
}
public function unfavoriteProduct(Request $request, $productId) {
if ((int) $productId > 0) {
ProductFavorite::where('session_id', session()->getId())->
where('product_id', $productId)->
delete();
// Send back an array of favorite products
return ProductFavorite::where('session_id', session()->getId())->
get()->
map(function ($productFavorite) {
return $productFavorite->product_id;
});
}
}
I just need to get the cookie code in here somehow.
This seems to me that it should be a very common situation (favorites, shopping carts, etc...), yet I can't find any tutorials that cover sessions with cookies appropriately.
Thank you in advance for any help you can give!
Please or to participate in this conversation.