karya solusi digital

Contoh Membuat Shopping Cart di Laravel 11

Admin
Admin 11 Sep 2024

Berikut ini adalah contoh sederhana untuk membuat Shopping Cart di Laravel 11. Dalam contoh ini, kita akan menggunakan session untuk menyimpan item di keranjang belanja (shopping cart):

1. Instalasi Laravel 11

Pertama, buat proyek Laravel 11 baru:

composer create-project --prefer-dist laravel/laravel laravel-shopping-cart

2. Membuat Model dan Migration

Kita akan membuat model Product untuk produk yang akan dimasukkan ke dalam keranjang belanja.

php artisan make:model Product -m

Edit migration create_products_table:

Schema::create('products', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->decimal('price', 8, 2);
    $table->integer('stock');
    $table->timestamps();
});

Jalankan migrasi:

php artisan migrate

3. Menambah Data Produk

Buat seeder untuk produk:

php artisan make:seeder ProductSeeder

Isi ProductSeeder:

use App\Models\Product;

public function run()
{
    Product::create([
        'name' => 'Product 1',
        'price' => 100.00,
        'stock' => 10,
    ]);

    Product::create([
        'name' => 'Product 2',
        'price' => 150.00,
        'stock' => 15,
    ]);
}

Jalankan seeder:

php artisan db:seed --class=ProductSeeder

4. Membuat Controller untuk Shopping Cart

Buat controller CartController untuk menangani fungsi tambah, hapus, dan lihat item di keranjang belanja.

php artisan make:controller CartController

Isi CartController:

use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class CartController extends Controller
{
    public function addToCart($id)
    {
        $product = Product::findOrFail($id);
        $cart = session()->get('cart', []);

        if(isset($cart[$id])) {
            $cart[$id]['quantity']++;
        } else {
            $cart[$id] = [
                "name" => $product->name,
                "quantity" => 1,
                "price" => $product->price,
            ];
        }

        session()->put('cart', $cart);
        return redirect()->back()->with('success', 'Product added to cart!');
    }

    public function removeFromCart($id)
    {
        $cart = session()->get('cart');
        if(isset($cart[$id])) {
            unset($cart[$id]);
            session()->put('cart', $cart);
        }

        return redirect()->back()->with('success', 'Product removed from cart!');
    }

    public function viewCart()
    {
        $cart = session()->get('cart');
        return view('cart', compact('cart'));
    }
}

5. Membuat Routing

Tambahkan rute untuk cart di routes/web.php:

use App\Http\Controllers\CartController;

Route::get('cart', [CartController::class, 'viewCart'])->name('cart.view');
Route::get('add-to-cart/{id}', [CartController::class, 'addToCart'])->name('cart.add');
Route::get('remove-from-cart/{id}', [CartController::class, 'removeFromCart'])->name('cart.remove');

6. Membuat Tampilan (View)

Buat file blade resources/views/cart.blade.php:

@extends('layouts.app')

@section('content')
<div class="container">
    <h1>Shopping Cart</h1>

    @if(session('success'))
        <div class="alert alert-success">
            {{ session('success') }}
        </div>
    @endif

    @if(session('cart'))
        <table class="table">
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Quantity</th>
                    <th>Price</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                @foreach(session('cart') as $id => $details)
                <tr>
                    <td>{{ $details['name'] }}</td>
                    <td>{{ $details['quantity'] }}</td>
                    <td>${{ $details['price'] }}</td>
                    <td>
                        <a href="{{ route('cart.remove', $id) }}" class="btn btn-danger">Remove</a>
                    </td>
                </tr>
                @endforeach
            </tbody>
        </table>
    @else
        <h3>No items in the cart</h3>
    @endif
</div>
@endsection

7. Testing Shopping Cart Tambahkan link di halaman produk untuk menambahkan ke cart.

Buka URL http://your-app-url/cart untuk melihat item di cart.

Ini adalah contoh sederhana dari Shopping Cart di Laravel 11.