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

Melodia's avatar

How do I create a unique session for a user that is not logged in

For this task, created an end-point that lists all products using VueX and the template has this:

<div v-for="p in products" class="col col-md-4">
    <div><span class="title">{{ p.title }}</span> | <span class="price">R{{ p.price }}</span> </div>
    <p>{{ p.description | counter }}</p>
    <button @click="order" class="add-cart btn btn-primary">Order Now</button>
</div>

When I click to order, an order method needs to get fired which will add that particular product into the cart.

methods: {
    order(){
        //update cart object
    }
}

However, to proceed to checkout, the user needs to be logged in and am using the laravel auth.

Since the cart details are to be stored in a cart object, the cart details need to be available even after the page refreshes to the login. and I assume I need to have a type of session for as soon as the user enters on the page for the very first time.

How can I achieve this? How can I let the system record the cart details before the user is logged in and remember it even after the page reloads?

Hope the explanation makes sense.

0 likes
1 reply
grenadecx's avatar

In laravel, by default all your routes put inside the web.php are using all of the middlewares defined in the "web" middleware group. Under app/Http/Kernel.php you can check:

    protected $middlewareGroups = [
        'web' => [
        // ...
            \Illuminate\Session\Middleware\StartSession::class,
        ]
    ];

As you can see, the middleware for creating a session is always active, that means even if the user isn't logged in, a unique session for that user has already been created. So you can store and return things from the session using the session() helper function or the Session facade.

It's possible that once you login, the session will be destroyed and a new one is created, I don't remember. If you want to keep the cart, you would need to store in in a variable, allow the session from the logincontroller to run and then readd the cart to the session.

Please or to participate in this conversation.