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

Raimondas's avatar

New to session. How to put this code in session ?

Hi, sessions is a new thing for me. I'm making a cart now and thinking how for non-registered user add products to his cart. This is my solution for registered user:

    public function add(Request $request, $id)
    {
        Cart::create([
            'user_id' => Auth::id(),
            'product_id' => $id,
            'quantity' => 5
        ]);
        return redirect()->back();
    }

I'm grabbing it's ID and then displaying his products in cart by his ID. But how to put this code in session ?

0 likes
4 replies
ohffs's avatar

Assuming they can add more than one thing to the cart, you'd maybe do something like :

// add an item to the cart
$request->session()->push('cart', $id);

// at checkout
$productIds = session('cart');
Raimondas's avatar

So if I pust this code in "add" function and when I press the "add to cart" button the product will add to session ?

Raimondas's avatar

Okay it seems to work.. I'm getting this when I do dd($productIds)

array:2 [▼
  0 => "1"
  1 => "1"
]

Is it good ?

@ohffs

How to get products titles, prices and quantities ?

ohffs's avatar
ohffs
Best Answer
Level 50

Just find them in the db, I think just $products = Products::find($productIds) or whatever your products model is called.

Please or to participate in this conversation.