DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on

How do you create a full backend API for an eCommerce website using PHP Laravel?

To create a full backend API for an eCommerce website using PHP and Laravel, you need to follow best practices for structuring a scalable and maintainable project. Laravel offers a rich set of tools to handle everything from routing, models, controllers, and middleware to database migrations, authentication, and API resources.

File and Folder Structure

Here is the recommended folder and file structure for a Laravel-based eCommerce backend API:



ecommerce-backend/
│
├── app/
│   ├── Console/
│   ├── Exceptions/
│   ├── Http/
│   │   ├── Controllers/
│   │   │   ├── AuthController.php        # Handles user authentication
│   │   │   ├── ProductController.php     # CRUD operations for products
│   │   │   ├── CategoryController.php    # CRUD operations for categories
│   │   │   ├── OrderController.php       # Order management
│   │   │   └── CartController.php        # Cart management
│   │   ├── Middleware/
│   │   ├── Requests/
│   │   ├── Resources/
│   ├── Models/
│   │   ├── User.php                      # User model for customer & admin accounts
│   │   ├── Product.php                   # Product model
│   │   ├── Category.php                  # Category model
│   │   ├── Order.php                     # Order model
│   │   └── Cart.php                      # Cart model
│   ├── Policies/
│   ├── Providers/
│   ├── Services/
│   └── Rules/
│
├── bootstrap/
│   ├── cache/
│   └── app.php
│
├── config/
│   ├── app.php                           # Core application configuration
│   ├── auth.php                          # Authentication config
│   ├── database.php                      # Database configuration (MySQL, PostgreSQL, etc.)
│   └── services.php                      # Third-party services config (Stripe, PayPal, etc.)
│
├── database/
│   ├── migrations/                       # Database migration files
│   │   ├── create_users_table.php
│   │   ├── create_products_table.php
│   │   ├── create_categories_table.php
│   │   ├── create_orders_table.php
│   │   └── create_carts_table.php
│   ├── seeders/                          # Database seeder files
│   │   └── DatabaseSeeder.php
│   ├── factories/                        # Model factories for test data
│
├── public/                               # Publicly accessible files (index.php, assets)
├── resources/
│   ├── lang/
│   └── views/                            # Blade templates (if used for web views)
│
├── routes/
│   ├── api.php                           # API routes for the eCommerce backend
│   ├── web.php                           # Web routes (if needed)
│
├── storage/                              # Storage for logs, caches, and compiled views
├── tests/                                # Unit and feature tests
│   ├── Feature/
│   └── Unit/
├── vendor/                               # Composer dependencies
├── .env                                  # Environment configuration
├── composer.json                         # Composer package configuration
├── artisan                               # Laravel command-line interface entry point
└── README.md                             # Project documentation


Enter fullscreen mode Exit fullscreen mode

Key Components

1. Models (app/Models/)

  • The Product, Category, Order, and Cart models represent the core business logic for the eCommerce API.
  • The User model handles authentication and user-specific functionality.

  • Documentation:

2. Controllers (app/Http/Controllers/)

  • Controllers like ProductController, CategoryController, OrderController, and CartController handle CRUD operations for their respective resources.
  • AuthController manages user registration, login, and token-based authentication (JWT or Laravel Passport).

  • Documentation:

3. API Routes (routes/api.php)

  • This file contains all the routes for the API, with versioning (e.g., /api/v1/products, /api/v1/orders).
  • It typically includes routes for authentication, product listings, and order management.

  • Documentation:

4. Database Migrations (database/migrations/)

  • Define tables and relationships for products, categories, users, orders, and carts using migrations.
  • Each table (e.g., products, categories, orders) will have its own migration file to set up the schema.

  • Documentation:

5. Authentication

  • Use Laravel Sanctum or Laravel Passport for token-based authentication.
  • Sanctum is lightweight and perfect for single-page applications (SPAs) or mobile apps, while Passport offers full OAuth2 capabilities for more complex use cases.

  • Documentation:

6. Requests (app/Http/Requests/)

  • Form request classes that validate incoming data before passing it to controllers, ensuring that only valid data is processed by the API.

  • Documentation:

7. Middleware (app/Http/Middleware/)

  • Middleware for tasks like JWT token validation, checking if the user is authenticated, handling CORS, or applying rate limiting.
  • Laravel provides several built-in middleware that can be used or customized as needed.

  • Documentation:

8. API Resources (app/Http/Resources/)

  • Transform models into JSON responses using API resources, allowing control over how data is returned to clients (e.g., mobile apps or frontend SPAs).

  • Documentation:

9. Services (app/Services/)

  • Separate service classes to handle business logic that may be reused across controllers (e.g., handling payment gateway integrations, email notifications).

  • Documentation:

10. Storage and Logs (storage/)

  • Used for storing logs, file uploads, and compiled Blade views if you use Laravel’s templating engine. Laravel also provides excellent logging capabilities out of the box.

  • Documentation:

11. Testing (tests/)

  • Laravel encourages unit testing and feature testing using PHPUnit. Tests can be written to ensure that products, categories, orders, and users are working as expected.

  • Documentation:

Environment Setup

  1. Install Laravel via Composer:


   composer create-project --prefer-dist laravel/laravel ecommerce-backend


Enter fullscreen mode Exit fullscreen mode
  1. Set Up Database:
    • Configure your database in the .env file (e.g., MySQL, PostgreSQL).
    • Run migrations to create the database schema:


   php artisan migrate


Enter fullscreen mode Exit fullscreen mode
  1. Install Authentication (JWT or Passport):

    • Install either Laravel Sanctum or Passport for authentication.
    • Configure user authentication and register your API routes.
  2. Run the Application:



   php artisan serve


Enter fullscreen mode Exit fullscreen mode
  1. Use a Tool like Postman or Insomnia to Test API Endpoints:
    • Interact with the API using Postman to perform CRUD operations on products, categories, users, orders, etc.

Recommended Packages for eCommerce

  • spatie/laravel-permission: For role-based access control (admin, customer).
  • omnipay: Payment gateway integration (Stripe, PayPal).
  • laravel/sanctum: For handling API authentication.
  • laravel-cashier: Subscription billing management.

Additional Documentation:

By following this structure, you can develop a full-featured, modular eCommerce backend API with Laravel that is easy to maintain and scalable for future growth.

If you enjoy my content and would like to support my work, you can buy me a coffee. Your support is greatly appreciated!

Disclaimer: This content is generated by AI.

Top comments (0)