Laravel e commerce tutorial Part 6: Implementing the Shopping Cart in Laravel E-Commerce

Part 6: Implementing the Shopping Cart in Laravel E-Commerce

In this section of the Laravel E-Commerce Tutorial, we’ll focus on implementing the shopping cart functionality. The shopping cart is a crucial component that allows users to add products, view the cart contents, and proceed to checkout.

6.1 Setting Up the Cart Model and Controller

Step 1: Create Cart Model

Generate a Cart model:

bash
php artisan make:model Cart -m

Edit the migration file to define the cart table schema:

php
// database/migrations/YYYY_MM_DD_create_carts_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCartsTable extends Migration
{
public function up()
{
Schema::create('carts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('product_id');
$table->integer('quantity');
$table->timestamps();

$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
});
}

public function down()
{
Schema::dropIfExists('carts');
}
}

Run the migration:

bash
php artisan migrate

Define relationships in the Cart model (app/Models/Cart.php):

php
// app/Models/Cart.php

use Illuminate\Database\Eloquent\Model;

class Cart extends Model
{
protected $fillable = ['user_id', 'product_id', 'quantity'];

public function user()
{
return $this->belongsTo(User::class);
}

public function product()
{
return $this->belongsTo(Product::class);
}
}

Step 2: Create Cart Controller

Generate a controller for managing the shopping cart:

bash
php artisan make:controller CartController

Define the necessary methods in the CartController for adding, updating, and removing items from the cart.

php
// app/Http/Controllers/CartController.php

use Illuminate\Http\Request;
use App\Models\Cart;

class CartController extends Controller
{
public function index()
{
// Display cart contents
}

public function add(Request $request)
{
// Add item to cart
}

public function update(Request $request, Cart $cart)
{
// Update item quantity in cart
}

public function remove(Cart $cart)
{
// Remove item from cart
}

public function checkout()
{
// Checkout process
}
}

6.2 Implementing Cart Views

Step 1: Create Cart Views

Create Blade views for the shopping cart functionality:

  • resources/views/cart/index.blade.php: Display the contents of the shopping cart.
  • resources/views/cart/checkout.blade.php: Display the checkout form.

Step 2: Define Cart Routes

Define routes for cart management in routes/web.php:

php
use App\Http\Controllers\CartController;

Route::get('/cart', [CartController::class, 'index'])->name('cart.index');
Route::post('/cart/add', [CartController::class, 'add'])->name('cart.add');
Route::patch('/cart/update/{cart}', [CartController::class, 'update'])->name('cart.update');
Route::delete('/cart/remove/{cart}', [CartController::class, 'remove'])->name('cart.remove');
Route::get('/cart/checkout', [CartController::class, 'checkout'])->name('cart.checkout');

6.3 Implementing Cart Functionality

Step 1: Update Product Views

Update the product views to include an “Add to Cart” button and handle cart actions:

php
{{-- resources/views/products/index.blade.php --}}
@foreach ($products as $product)
{{-- Existing product details --}}
<form action="{{ route('cart.add') }}" method="post">
@csrf
<input type="hidden" name="product_id" value="{{ $product->id }}">
<input type="number" name="quantity" value="1" min="1">
<button type="submit">Add to Cart</button>
</form>
@endforeach

Step 2: Implement Cart Controller Methods

Implement the methods in the CartController to handle adding, updating, and removing items from the cart.

php
// app/Http/Controllers/CartController.php

use Illuminate\Support\Facades\Auth;

class CartController extends Controller
{
public function index()
{
$user = Auth::user();
$cartItems = $user->cartItems;

return view('cart.index', compact('cartItems'));
}

public function add(Request $request)
{
$request->validate([
'product_id' => 'required|exists:products,id',
'quantity' => 'required|integer|min:1',
]);

$user = Auth::user();
$user->cartItems()->updateOrCreate(
['product_id' => $request->product_id],
['quantity' => $request->quantity]
);

return redirect()->route('cart.index')->with('success', 'Item added to cart.');
}

public function update(Request $request, Cart $cart)
{
$request->validate([
'quantity' => 'required|integer|min:1',
]);

$cart->update(['quantity' => $request->quantity]);

return redirect()->route('cart.index')->with('success', 'Cart updated.');
}

public function remove(Cart $cart)
{
$cart->delete();

return redirect()->route('cart.index')->with('success', 'Item removed from cart.');
}

public function checkout()
{
// Implement checkout logic
}
}

Step 3: Update Cart Views

Update the cart views to display cart contents and allow users to update or remove items.

php
{{-- resources/views/cart/index.blade.php --}}
@foreach ($cartItems as $cartItem)
<p>Product: {{ $cartItem->product->name }}</p>
<p>Quantity: {{ $cartItem->quantity }}</p>
<form action="{{ route('cart.update', $cartItem->id) }}" method="post">
@csrf
@method('PATCH')
<input type="number" name="quantity" value="{{ $cartItem->quantity }}" min="1">
<button type="submit">Update</button>
</form>
<form action="{{ route('cart.remove', $cartItem->id) }}" method="post">
@csrf
@method('DELETE')
<button type="submit">Remove</button>
</form>
@endforeach

{{-- resources/views/cart/checkout.blade.php --}}
<form action="{{ route('cart.checkout') }}" method="post">
@csrf
{{-- Checkout form fields --}}
<button type="submit">Proceed to Checkout</button>
</form>

6.4 Summary

Congratulations! You’ve successfully implemented the shopping cart functionality in your Laravel E-Commerce application. Users can add products to their cart, view and update cart contents, and proceed to checkout. In the next part of the tutorial, we’ll focus on implementing the order management system. Stay tuned for the next steps!