0

I want to create my own shopping cart

I would like to know what is the way to store various items and then show the items in the cart

public function __construct()
{
    if(!\Session::has('cart')) \Session::put('cart', array());
}

my question is what code do I use to show the cart and then insert items inside it

user13523236
  • 135
  • 1
  • 14
  • Have a shopping cart array saved in a session. Each time user adds, add to the array and save in session. When you need to fetch everything, grab the array from the session – djunehor May 16 '20 at 20:17
  • Take a look at here: https://stackoverflow.com/a/37338994/6908226 – iazaran May 16 '20 at 20:43

1 Answers1

0

While this is not a strictly Laravel solution, it is a relatively simple and well supported (browser compatible) way to store simple session data on the client side. I do this using sessionStorage. Take a look at the sessionStorage documentation here.

Example JS:

// Save data to sessionStorage
sessionStorage.setItem('cart', 'item_id');

// Get saved data from sessionStorage
let data = sessionStorage.getItem('cart');

// Remove saved data from sessionStorage
sessionStorage.removeItem('cart');

// Remove all saved data from sessionStorage
sessionStorage.clear();

A shopping cart would usually store several different items and while sessionStorage does not store arrays, the workaround is to convert the comma seperated string to an array using split(",").

Example:

//if cart has value of 11,12,13,14,15
var ex1 = sessionStorage.getItem('cart').split(',');
//ex1 would be [11,12,13,14,15]

//without split(',')
var ex2 = sessionStorage.getItem('cart');
//ex2 would be 11,12,13,14,15
cedes
  • 74
  • 2