Overview
TheCartController handles all shopping cart operations for authenticated users, including viewing cart items, adding products, and removing items.
Location: app/Http/Controllers/CartController.php
Middleware: auth (all routes require authentication)
Methods
index()
Display the authenticated user’s shopping cart with all items.Returns the cart view with items and count
GET /cart
Route Name: cart.index
Middleware: auth
Implementation:
Collection of Cart models with eager-loaded Food relationshipsEach cart item contains:
id- Cart item IDuser_id- User IDfood_id- Food item IDquantity- Quantity in cartfood- Related Food model with all details
Total number of items in the cart
- Redirects to login if user is not authenticated
- Only shows items belonging to the authenticated user
store()
Add a food item to the cart or update quantity if it already exists.HTTP request with quantity
Food model instance (route-model binding)
Redirects back with success/error message
POST /cart/{food}
Route Name: cart.store
Middleware: auth
Implementation:
Quantity to add to cart (minimum: 1)
- Uses
updateOrCreateto prevent duplicate cart entries - If the food item already exists in cart, updates the quantity
- If the food item doesn’t exist, creates a new cart entry
- Validates that user is authenticated before processing
- Requires authentication
- Associates cart items with the authenticated user
- Route-model binding ensures the food item exists
destroy()
Remove an item from the cart.Cart model instance (route-model binding)
Redirects back with success message
DELETE /cart/{cart}
Route Name: cart.destroy
Middleware: auth
Implementation:
- Requires authentication
- Verifies that the cart item belongs to the authenticated user
- Returns 403 Forbidden if user tries to delete another user’s cart item
- If cart item doesn’t belong to user:
403 No autorizado - If user is not authenticated:
403 No autorizado
Usage Examples
Add Item to Cart
Remove Item from Cart
Display Cart
Data Relationships
Cart Model
The Cart model should have the following relationships:Database Schema
Thecarts table should include:
id- Primary keyuser_id- Foreign key to users tablefood_id- Foreign key to foods tablequantity- Integer, quantity of itemscreated_at- Timestampupdated_at- Timestamp
user_id + food_id (prevents duplicate entries)