4

I am trying to store data into the Laravel session on each AJAX call from the vue.js.

I want to add a product in Laravel cart using session but it's not storing any kind of session data. I have also added web middleware but no luck.

api.php

<?php
    Route::group(['namespace' => 'Api'],function(){
        Route::resource('product','ProductController');
        Route::post('add-to-cart','ProductController@addToCart');
    });

ProductController.php

<?php
    public function addToCart(Request $request){
    $product = $request->all();

    $cart = Session::get('cart');
    $cart[$product['id']] = $product;
    Session::push('cart', $cart);

    return Response::json(['success' => true, 'cart_items' => Session::get('cart')]);
}

ProductListComponene.vue

addToCartProduct(product){
    fetch('api/add-to-cart',{
        method: 'post',
        body:JSON.stringify(product),
        headers:{
            'content-type':'application/json'
        }
    })
    .then(res => res.json())
    .then(res => {
        console.log(res);
    })
    .catch(err => console.log(err));
}                 

1 Answer 1

6

All of your routes are registered in api middleware and if you check the app/Http/Kernel.php file, you will see the it doesn't have StartSession middelware registered. So you have to start the session first in order to save data to the session.

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

Added this \Illuminate\Session\Middleware\StartSession::class, into the middleware and working fine now. Thanks.
also good to take a look on this answer of mine, related to the session drivers stackoverflow.com/a/53253184/2693543
this dismantled error messages on every other blade for me. very annoying.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.