Get Appointment

t

Building a Laravel Shopping Cart System with Darryldecode/LaravelShoppingCart: A Step-by-Step Tutorial

  • Vfix Technology
  • 22 Apr 2024
  • Website Development ,  Laravel
  • 58 Views

In the bustling realm of e-commerce development, Laravel stands tall as one of the most preferred frameworks due to its simplicity, elegance, and robustness. If you're looking to enhance your Laravel skills and delve into the world of building a sophisticated shopping cart system, you're in the right place. In this tutorial, we'll guide you through the process of implementing a feature-rich shopping cart using the powerful Darryldecode/LaravelShoppingCart package.

Getting Started

Before we embark on our journey, let's ensure we have a Laravel application up and running. If you haven't already, install Laravel by following the official documentation. Once you have your Laravel project set up, we can proceed with integrating the shopping cart functionality.

Integrating Darryldecode/LaravelShoppingCart

The Darryldecode/LaravelShoppingCart package simplifies the process of implementing a shopping cart system in Laravel applications. Begin by installing the package via Composer:

composer require darryldecode/cart

Next, let's set up the necessary routes to handle cart operations. In your web.php file, define routes for adding items to the cart, updating quantities, removing items, and viewing the cart.

<?php

use Illuminate\Support\Facades\Route;
use App\Models\Product;
use App\Http\Controllers\CartController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('/', function () {
    $products = Product::all();
    return view('welcome',compact('products'));
});

Route::get('cart',[CartController::class,'cart'])->name('cart');
Route::get('add-cart/{productId}',[CartController::class,'addCart'])->name('add.cart');

//
Route::get('add-quantity/{productId}',[CartController::class,'addQuantity'])->name('add.quantity');

Route::get('decrease-quantity/{productId}',[CartController::class,'decreaseQuantity'])->name('decrease.quantity');

Route::get('remove-item/{productId}',[CartController::class,'removeItem'])->name('remove.item');

Route::get('clear',[CartController::class,'clearCart'])->name('clear');

Create migrarion & factory for products:

php artisan make:model Product -mf

Product Migration:

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('image');
            $table->string('price');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('products');
    }
};

Now let’s make factory:

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Product>
 */
class ProductFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'name' => fake()->sentence(),
            'image' => fake()->imageUrl(),
            'price' => rand(99,999)
        ];
    }
}

Seed the data:

<?php

namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        // \App\Models\User::factory(10)->create();

        // \App\Models\User::factory()->create([
        //     'name' => 'Test User',
        //     'email' => '[email protected]',
        // ]);

        \App\Models\Product::factory(6)->create();
    }
}

Laravel Route file:

<?php

use Illuminate\Support\Facades\Route;
use App\Models\Product;
use App\Http\Controllers\CartController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('/', function () {
    $products = Product::all();
    return view('welcome',compact('products'));
});

Route::get('cart',[CartController::class,'cart'])->name('cart');
Route::get('add-cart/{productId}',[CartController::class,'addCart'])->name('add.cart');

//
Route::get('add-quantity/{productId}',[CartController::class,'addQuantity'])->name('add.quantity');

Route::get('decrease-quantity/{productId}',[CartController::class,'decreaseQuantity'])->name('decrease.quantity');

Route::get('remove-item/{productId}',[CartController::class,'removeItem'])->name('remove.item');

Route::get('clear',[CartController::class,'clearCart'])->name('clear');

Cart Controller:

<?php

namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;

class CartController extends Controller
{
    public function cart()
    {
        $total = \Cart::getTotal();
        $items = \Cart::getContent();
        return view('cart',compact('items','total'));
    }

    public function addCart($productId)
    {
        $product = Product::findOrFail($productId);

        \Cart::add(array(
            'id' => $productId,
            'name' => $product->name,
            'price' => $product->price,
            'quantity' => 1,
            'attributes' => array(
                'image' => $product->image,

            ),
            'associatedModel' => $product
        ));

        return redirect()->route('cart')->with('success','Item has been addeed to the cart');
    }

    public function addQuantity($productId)
    {
        \Cart::update($productId,[
            'quantity' => +1
        ]);

        return back()->with('success','Quantity has been increased');
    }

    public function decreaseQuantity($productId)
    {
        \Cart::update($productId,[
            'quantity'=> -1
        ]);

        return back()->with('success','item quantity has been decreased');
    }

    public function removeItem($productId)
    {
        \Cart::remove($productId);
        return back()->with('success','item has been removed from the cart');
    }

    public function clearCart()
    {
        \Cart::clear();
        return back()->with('success','There is no item in your cart');
    }
}

Let’s Add Main page blade & name welcome.blade.php within resources/views/welcome.blade.php to run loop of product catalogs:

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">

</head>

<body>
    <nav class="navbar navbar-expand-lg bg-body-tertiary bg-dark" data-bs-theme="dark">
        <div class="container">
            <a class="navbar-brand" href="#">Vfix Technology</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse"
                data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
                aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav ms-auto mb-2 mb-lg-0">
                    <li class="nav-item">
                        <a class="nav-link active" aria-current="page" href="#">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/cart">Cart</a>
                    </li>

            </div>
        </div>
    </nav>

    <section class="py-5">
        <div class="container py-5">
            <div class="row g-4">
               @foreach ($products as $product)
               <div class="col-md-4">
                <div class="card">
                    <img src="{{ $product->image }}" class="card-img-top"
                        alt="...">
                    <div class="card-body">
                        <h5 class="card-title">{{ $product->name }}</h5>
                        <p>{{ Number::currency($product->price) }}</p>

                        <a href="{{ route('add.cart',$product->id) }}" class="btn btn-primary">Add cart</a>
                    </div>
                </div>
            </div>
               @endforeach

            </div>
        </div>
    </section>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous">
    </script>

</body>

</html>

Now create a new blade for cart page: resources/views/cart.blade.php

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Cart</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous" />


</head>

<body>
    <nav class="navbar navbar-expand-lg bg-body-tertiary bg-dark" data-bs-theme="dark">
        <div class="container">
            <a class="navbar-brand h3 bw-bold" href="#">VFX Store</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse"
                data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
                aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav ms-auto mb-2 mb-lg-0">
                    <li class="nav-item">
                        <a class="nav-link" href="http://127.0.0.1:8000">Products</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" aria-current="page" href="/cart">Cart (1)</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
    <!-- cart + summary -->
    <section class="bg-light my-5">
        <div class="container">
            <div class="row">
                <!-- cart -->
                <div class="col-lg-9">
                    @if (Session::has('success'))
                        <div class="alert alert-success">
                            {{ session()->get('success') }}
                        </div>
                    @endif

                    <div class="card border shadow-0">
                        <div class="m-4">
                            <div class="mb-3">
                                <span class="card-title mb-4 h4">Your shopping cart</span>
                                <a href="{{ route('clear') }}" class="float-end">Clear
                                    All</a>:
                            </div>
                            <hr />
                            @foreach ($items as $item)
                            <div class="row gy-3 mb-4">
                                <div class="col-lg-5">
                                    <div class="me-lg-5">
                                        <div class="d-flex">
                                            <img src="{{ $item->attributes->image }}"
                                                class="border rounded me-3" style="width: 96px; height: 96px" />
                                            <div class="">
                                                <a href="#" class="nav-link">{{ $item->name }}</a>
                                                <p class="text-muted">{{ Number::currency($item->price) }}</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div
                                    class="col-lg-2 col-sm-6 col-6 d-flex flex-row flex-lg-column flex-xl-row text-nowrap">
                                    <td>
                                        <div class="input-group bootstrap-touchspin">
                                            <span class="input-group-btn"><a
                                                    href="{{ route('decrease.quantity',$item->id) }}"
                                                    class="btn btn-default bootstrap-touchspin-down"
                                                    type="button">-</a></span><span
                                                class="input-group-addon bootstrap-touchspin-prefix"
                                                style="display: none"></span>
                                            <input type="text" name="" value="{{ $item->quantity }}"
                                                class="form-control mx-1 px-3" />
                                            <span class="input-group-addon bootstrap-touchspin-postfix"
                                                style="display: none"></span><span class="input-group-btn">
                                                <a href="{{ route('add.quantity',$item->id) }}"
                                                    class="btn btn-default bootstrap-touchspin-up"
                                                    type="button">+</a></span>
                                        </div>
                                    </td>
                                    <div class="">
                                        <p class="h6">
                                            {{ $item->quantity * $item->price }}
                                        </p>
                                    </div>
                                </div>
                                <div
                                    class="col-lg col-sm-6 d-flex justify-content-sm-center justify-content-md-start justify-content-lg-center justify-content-xl-end mb-2">
                                    <div class="float-md-end">
                                        <a href="{{ route('remove.item',$item->id) }}"
                                            class="btn btn-light border text-danger icon-hover-danger">
                                            Remove</a>
                                    </div>
                                </div>
                            </div>
                            @endforeach

                        </div>

                        <div class="border-top pt-4 mx-4 mb-4">
                            <p>
                                <i class="fas fa-truck text-muted fa-lg"></i> Free Delivery
                                within 1-2 weeks
                            </p>
                            <p class="text-muted">
                                Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
                                do eiusmod tempor incididunt ut labore et dolore magna aliqua.
                                Ut enim ad minim veniam, quis nostrud exercitation ullamco
                                laboris nisi ut aliquip
                            </p>
                        </div>
                    </div>
                </div>
                <!-- cart -->
                <!-- summary -->
                <div class="col-lg-3">
                    <div class="card mb-3 border shadow-0">
                        <div class="card-body">
                            <form>
                                <div class="form-group">
                                    <label class="form-label">Have coupon?</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control border" name=""
                                            placeholder="Coupon code" />
                                        <button class="btn btn-light border">Apply</button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <div class="card shadow-0 border">
                        <div class="card-body">






                            <hr />
                            <div class="d-flex justify-content-between">
                                <p class="mb-2">Total price:</p>
                                <p class="mb-2 fw-bold">{{ Number::currency($total,'usd') }}</p>
                            </div>

                            <div class="mt-3">
                                <a href="#" class="btn btn-success w-100 shadow-0 mb-2">
                                    Make Purchase
                                </a>
                                <a href="#" class="btn btn-light w-100 border mt-2">
                                    Back to shop
                                </a>
                            </div>
                        </div>
                    </div>

                </div>
                <!-- summary -->
            </div>
        </div>
    </section>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous">
    </script>


</body>

</html>

 



+91 8447 525 204 Request Estimate