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

mostafasadek's avatar

I can't understand the Cart session

Hi, I just want to understand for whati this 'cart ' refer to in the session , i mean if i changed it to 'cartttt' or anything else is this will effect and what it will effect , I really i don't understand the sessions here

public function addToCart(Product $product) {

        if (session()->has('cart')) {
            $cart = new Cart(session()->get('cart'));
        } else {
            $cart = new Cart();
        }
        $cart->add($product);
        //dd($cart);
        session()->put('cart', $cart);
        return redirect()->route('product.index')->with('success', 'Product was added');
    }
0 likes
7 replies
Braunson's avatar

Cart is a session variable with the ability to add items into your users session's cart. If you change it (i.e. everywhere it's used), the existing users with cart's will be empty as your using a different variable.

Sessions are a way to store information about the user across multiple requests

https://laravel.com/docs/5.8/session#introduction

cart is just a specific named "basket" of information you are referencing.

mostafasadek's avatar

thanks for your reply ,But is it standard in laravel to be name with 'cart' ?

tykus's avatar

is it standard in laravel to be name with 'cart'

No. You could call it anything basket, shopping_cart, bucket, etc. Whatever you call it is the key into the Session with the value being the contents of the Cart, so wherever the Cart (and its contents) are created, read, updated, and destroyed should be using the same key.

jlrdw's avatar

Jeffrey also has some basic free PHP courses, it wouldn't hurt for you to take them.

mostafasadek's avatar

Thank but i have problem with understanding the if session() ,, Is it condition to do what i am very sorry but i really want to understand it 100% with simple way

tykus's avatar

if(session()->has('cart')) is exactly how it reads, i.e. if the Session has a cart then $cart gets the contents of the cart from the session, otherwise, a new empty Cart is created.

Please or to participate in this conversation.