How to create a shopping cart in Laravel

Updated: January 16, 2024 By: Guest Contributor Post a comment

Introduction

Shopping carts are an integral part of any e-commerce platform. Laravel, being one of the most popular PHP frameworks, provides an excellent environment for building a secure and functional shopping cart. In this tutorial, we’ll walk through the process of creating a shopping cart in Laravel from scratch. We’ll cover everything from setting up the basics to implementing advanced features. By the end, you will have a running shopping cart that you can integrate into any Laravel e-commerce application.

Setting Up

Before we dive into the code, make sure you have Laravel installed on your machine. If not, head to the official Laravel documentation for installation instructions. Create a new Laravel project or navigate to your existing one to get started.

laravel new shopping-cart

Database Configuration

Begin by configuring your database settings in the .env file. Make sure your database connection details are accurate.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_shopping_cart
DB_USERNAME=root
DB_PASSWORD=

Creating Models and Migrations

We’ll need two main models: Product for the items that can be bought and CartItem for the items in the shopping cart. Start by creating these models and their corresponding migrations with Eloquent.

php artisan make:model Product -m
php artisan make:model CartItem -m

Define the migrations and models based on your application’s needs. For simplicity, we will include only the essential fields.

// database/migrations/[timestamp]_create_products_table.php
...
Schema::create('products', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->decimal('price', 8, 2);
    $table->text('description');
    $table->timestamps();
});

// database/migrations/[timestamp]_create_cart_items_table.php
...
Schema::create('cart_items', function (Blueprint $table) {
    $table->id();
    $table->foreignId('product_id')->constrained();
    $table->integer('quantity');
    $table->timestamps();
});

Building the Shopping Cart Logic

We will create a simple shopping cart system that allows users to add items to the cart, update item quantities, and remove items from the cart. The cart will be stored in the session to keep it both stateful across multiple requests and unique to the user.

Let’s write our cart logic in a dedicated class, you might want to generate it using the artisan command.

php artisan make:controller CartController

In your CartController, add the necessary methods for adding items to the cart, updating them, and removing them.

...
public function addToCart(Request $request)
{
    // Adding to cart logic
}

public function updateCart(Request $request)
{
    // Updating cart logic
}

public function removeFromCart(Request $request)
{
    // Removing from cart logic
}
…

Inside these methods, you would typically interact with Laravel’s session to store and manage the cart’s contents. Here’s what adding an item to the cart might look like:

...
public function addToCart(Request $request)
{
    $product = Product::findOrFail($request->id);
    $cart = session()->get('cart', []);

    // Check if the item is in the cart and increment the quantity
    if(isset($cart[$request->id])) {
        $cart[$request->id]['quantity']++;
    } else {
        // If not in the cart, add it with quantity as 1
        $cart[$request->id] = [
            "name" => $product->name,
            "quantity" => 1,
            "price" => $product->price
        ];
    }
    session()->put('cart', $cart);

    return redirect()->back()->with('success', 'Product added to cart successfully!');
}
...

Displaying the Cart

For the user to view their cart items, we’ll need a route and a corresponding view. Start by creating a new route in the web.php file.

Route::get('/cart', 'CartController@index');

In the CartController, create the index method which will return the view along with the cart items.

public function index()
{
    $cart = session()->get('cart');

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

Create the view file resources/views/cart/index.blade.php. Here, you will iterate over the $cart array and display the cart items.

<!-- resources/views/cart/index.blade.php -->
<ul>
    @foreach(session('cart') as $id => $details)>
        <li>{{ $details['name'] }} - {{ $details['quantity'] }}</li>
    @endforeach
</ul>

That’s it for displaying the cart. Every time you add an item, it will show up here.

Conclusion

In this tutorial, we’ve demonstrated how to build a simple but fully functional shopping cart in Laravel. As a next step, you might want to explore additional features like integrating a payment gateway or adding user authentication to associate a cart with a user. The techniques outlined in this guide provide a strong foundation for creating a robust e-commerce platform using Laravel.

Happy coding!