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));
}                 
Udhav Sarvaiya
  • 9,380
  • 13
  • 53
  • 64
Mayank Dudakiya
  • 3,635
  • 35
  • 35

1 Answers1

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

Mayank Dudakiya
  • 3,635
  • 35
  • 35
Gopal Kildoliya
  • 649
  • 5
  • 21
  • Added this `\Illuminate\Session\Middleware\StartSession::class,` into the middleware and working fine now. Thanks. – Mayank Dudakiya Feb 25 '19 at 06:40
  • 1
    also good to take a look on this answer of mine, related to the session drivers https://stackoverflow.com/a/53253184/2693543 – Shobi Feb 25 '19 at 06:50
  • this dismantled error messages on every other blade for me. very annoying. – caro Jul 14 '22 at 16:23