I'm buiding an e-commerce website in Laravel 7 and I'm trying to do a shopping cart with sessions. I know there are many packages I can use for, and I tried to use some of them with no success, but that's not the problem I wanna talk about here.
At first, the code is very simple, I have two methods: index and add.
index method
public function index(){
var_dump(session()->get('testCart'));
die();
return view("cart.index");
}
add method
public function add(){
$cart = [
"id" => 1,
"product" => "PS4",
"qty" => 1,
"totalPrice" => 300
];
session(["testCart" => array($cart)]);
return view('cart.index');
}
That's the code, as I said before, very simple for this test. I also have a route to add products to my cart.
routes/web.php
// CART
Route::get('/carrito', 'CartController@index')->name("cart.index");
Route::get('/carrito/add', 'CartController@add')->name("cart.add");
The first step I do, of course, is go to /carrito/add and then to the route /carrito. But when I go to this last route, the code doesn't find my cart session and it gives me a NULL.
NOTE: I have noticed that sometimes the index method finds my session and shows its value. But most of the time it doesn't.
I hope my English was clear enough to describe my problem properly, if you need more code or information, make me know it.
Thanks in advance, Ciro.