shopping cart laravel tutorial code example
Example: laravel 7 shopping cart tutorial
public function addToCart($id)
{
$product = Product::find($id);
if(!$product) {
abort(404);
}
$cart = session()->get('cart');
if(!$cart) {
$cart = [
$id => [
"name" => $product->name,
"quantity" => 1,
"price" => $product->price,
"photo" => $product->photo
]
];
session()->put('cart', $cart);
return redirect()->back()->with('success', 'Product added to cart successfully!');
}
if(isset($cart[$id])) {
$cart[$id]['quantity']++;
session()->put('cart', $cart);
return redirect()->back()->with('success', 'Product added to cart successfully!');
}
$cart[$id] = [
"name" => $product->name,
"quantity" => 1,
"price" => $product->price,
"photo" => $product->photo
];
session()->put('cart', $cart);
return redirect()->back()->with('success', 'Product added to cart successfully!');
}