One way to implement a cart logic in Laravel is to use the session to store the cart items. Here's an example implementation:
- Create a Cart class that will handle the cart operations:
<?php
namespace App;
class Cart
{
public function add($product)
{
$cart = session()->get('cart');
// If the product is already in the cart, increase its quantity
if (isset($cart[$product->id])) {
$cart[$product->id]['quantity']++;
} else {
// Otherwise, add the product to the cart
$cart[$product->id] = [
'product' => $product,
'quantity' => 1,
];
}
session()->put('cart', $cart);
}
public function remove($productId)
{
$cart = session()->get('cart');
unset($cart[$productId]);
session()->put('cart', $cart);
}
public function clear()
{
session()->forget('cart');
}
public function items()
{
return session()->get('cart', []);
}
public function count()
{
$cart = session()->get('cart', []);
return count($cart);
}
public function total()
{
$cart = session()->get('cart', []);
$total = 0;
foreach ($cart as $item) {
$total += $item['product']->price * $item['quantity'];
}
return $total;
}
}
- In your controller, you can use the Cart class to add, remove, and retrieve items from the cart:
<?php
namespace App\Http\Controllers;
use App\Cart;
use App\Product;
use Illuminate\Http\Request;
class CartController extends Controller
{
public function add(Request $request, Product $product)
{
$cart = new Cart();
$cart->add($product);
return redirect()->back();
}
public function remove(Request $request, $productId)
{
$cart = new Cart();
$cart->remove($productId);
return redirect()->back();
}
public function clear(Request $request)
{
$cart = new Cart();
$cart->clear();
return redirect()->back();
}
public function index(Request $request)
{
$cart = new Cart();
$items = $cart->items();
$total = $cart->total();
return view('cart.index', compact('items', 'total'));
}
}
- In your views, you can display the cart items and total:
<h1>Cart</h1>
@if ($items)
<table>
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach ($items as $item)
<tr>
<td>{{ $item['product']->name }}</td>
<td>{{ $item['quantity'] }}</td>
<td>{{ $item['product']->price }}</td>
<td>{{ $item['product']->price * $item['quantity'] }}</td>
<td>
<form action="{{ route('cart.remove', $item['product']->id) }}" method="POST">
@csrf
@method('DELETE')
<button type="submit">Remove</button>
</form>
</td>
</tr>
@endforeach
</tbody>
<tfoot>
<tr>
<td colspan="3">Total</td>
<td>{{ $total }}</td>
<td>
<form action="{{ route('cart.clear') }}" method="POST">
@csrf
<button type="submit">Clear</button>
</form>
</td>
</tr>
</tfoot>
</table>
@else
<p>Your cart is empty.</p>
@endif
Note: This is just a basic implementation of a cart logic. Depending on your requirements, you may need to add more features such as updating the quantity of items, applying discounts, etc.