How to Build a Shopping Cart in Laravel 12 (Step-by-Step) Part 1
In this tutorial, we will Learn how to create a fully functional shopping cart in Laravel 12.
The user can browse products, add them to the cart, view and update them, and finally proceed to payment using the Stripe payment gateway.
Create the products table
First, we need a new Product migration and Model. Create them and add the code below inside the 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->longText('description');
$table->integer('price');
$table->string('image');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('products');
}
};
Create the product factory
Next, we need a product factory create it and add the code below inside:
<?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()->word(),
'description' => fake()->paragraph(),
'price' => fake()->numberBetween(1,100),
'image' => "https://picsum.photos/id/".fake()->numberBetween(0,100)."/640/400",
];
}
}
Create the product seeder
Next, we need a product seeder create it and add the code below inside:
<?php
namespace Database\Seeders;
use App\Models\Product;
use Illuminate\Database\Seeder;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
class ProductSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
Product::factory(20)->create();
}
}
Update the DatabaseSeeder.php file
Next, we need to update the file DatabaseSeeder.php, add the code below inside:
<?php
namespace Database\Seeders;
use App\Models\User;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*/
public function run(): void
{
// User::factory(10)->create();
// User::factory()->create([
// 'name' => 'Test User',
// 'email' => 'test@example.com',
// ]);
$this->call([
ProductSeeder::class
]);
}
}
Update the Product Model
Inside the Product Model, add the code below, and run the commands:
php artisan migrate
php artisan db:seed
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Product extends Model
{
use HasFactory;
}