Reputation: 3869
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));
}
Upvotes: 4
Views: 2891
Reputation: 649
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.
Upvotes: 6