Laravel 8 E-Commerce - Shopping Cart Using Database

In this video, we will learn how to create a shopping cart using a database.

Until now, we were using a session-based shopping cart. Now, we will add a database table to store cart items for each user individually.

First, let's create a migration for the shopping cart. Switch to the command prompt and execute the following command:


php artisan vendor:publish --provider="Gloudemans\Shoppingcart\ShoppingcartServiceProvider" --tag="migrations"

Now, switch to the project and let's examine the migration. Go to the database directory and open the shopping cart migration file. Here, you can see the columns that are added to store cart items for each user:


public function up()
{
Schema::create(config('cart.database.table'), function (Blueprint $table) {
$table->string('identifier');
$table->string('instance');
$table->longText('content');
$table->nullableTimestamps();

$table->primary(['identifier', 'instance']);
});
}

Next, let's run the migration. Switch to the command prompt and type the following command:


php artisan migrate

Now, let's store the cart items in the table. Open the ShopComponent class file and inside the render method, first check if the user is authenticated or not, and then call the store method:


if(Auth::check())
{
Cart::instance('cart')->store(Auth::user()->email);
}

Make sure you have imported Auth at the top:


use Illuminate\Support\Facades\Auth;

Next, open the CartComponent class file and inside the render method, write the same code. First, check if the user is authenticated or not, and then call the store method:


if(Auth::check())
{
Cart::instance('cart')->store(Auth::user()->email);
}

Make sure you have imported Auth at the top:


use Illuminate\Support\Facades\Auth;

Now, let's restore the shopping cart after the user logs in. Go to the HomeComponent class file and inside the render method, first check if the user is authenticated or not, and then call the restore method:


if(Auth::check())
{
Cart::instance('cart')->restore(Auth::user()->email);
}

Make sure you have imported Auth at the top:


use Illuminate\Support\Facades\Auth;

That's it! Let's test the functionality.

Switch to the browser and refresh the page. Log in with a user's credentials, add some items to the cart, and then log out. You will see that the cart is empty.

Log in again with the same user's credentials, and you will see the cart items for that user. If you log in with different user credentials, you will see an empty cart.

Add some products to the cart, log out, and then log in again with the first user's credentials. You will see the cart items for that user.

In this way, you can create a shopping cart using a database.