PHPackages                             adityapratamaf/laravel-cleanarchitecture-cqrs - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. adityapratamaf/laravel-cleanarchitecture-cqrs

ActiveProject[Framework](/categories/framework)

adityapratamaf/laravel-cleanarchitecture-cqrs
=============================================

Laravel 12 Clean Architecture + CQRS (API + Blade)

v1.0.0(6d ago)01↓100%MITPHPPHP ^8.2

Since Mar 16Pushed 6d agoCompare

[ Source](https://github.com/adityapratamaf/Laravel-CleanArchitecture-CQRS)[ Packagist](https://packagist.org/packages/adityapratamaf/laravel-cleanarchitecture-cqrs)[ RSS](/packages/adityapratamaf-laravel-cleanarchitecture-cqrs/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (10)Versions (2)Used By (0)

```
# Laravel Clean Architecture + CQRS Starter Template

Starter template Laravel 12 yang menggunakan **Clean Architecture + CQRS** dengan struktur yang sederhana, scalable, rapi, dan tidak over-engineered.

Template ini dirancang agar bisa digunakan untuk:

* REST API
* Web UI (Blade)
* Proyek menengah sampai terbesar
* Starter untuk microservice atau modular monolith
* Senior laravel architecture template

---

## ✨ Features

* ✅ Laravel 12
* ✅ Clean Architecture
* ✅ CQRS Pattern
* ✅ DTO-based data transfer
* ✅ CommandBus & QueryBus
* ✅ Global API Exception Handler
* ✅ Support **API** dan **Web Blade**
* ✅ Laravel Sanctum Authentication
* ✅ Custom Pagination Helper
* ✅ Custom Crypto Helper
* ✅ Modular folder structure
* ✅ Routes berada di `app/Presentation/Routes`
* ✅ Views berada di `app/Presentation/Views`
* ✅ Contoh module: **User** dan **Product** + migration + seeder
* ✅ Create new module with artisan
* ✅ Ready for Packagist template usage

---

## 📋 Requirements

* PHP `^8.2`
* Composer
* Database (MySQL/PostgreSQL/SQLite)

---

## 🧠 Clean Architecture & CQRS

### 🏛 Clean Architecture

Diperkenalkan oleh **Robert C. Martin (Uncle Bob)**.

Tujuan:

* Memisahkan business logic dari framework
* Meningkatkan testability
* Mengurangi ketergantungan pada database & UI
* Membuat sistem lebih scalable

#### 🔁 Dependency Rule

> Dependensi hanya boleh mengarah ke dalam (ke Domain).

```text
Framework / DB / UI
        ↓
Infrastructure
        ↓
Application
        ↓
Domain (Core Business)
```

Domain:

* Tidak tahu Laravel
* Tidak tahu HTTP
* Tidak tahu database

---

### ⚡ CQRS

Diperkenalkan oleh **Greg Young**.

Memisahkan:

* ✍ Command → Mengubah state
* 📖 Query → Mengambil data

Tujuan:

* Optimasi read & write
* Mengurangi kompleksitas
* Memudahkan scaling

---

## 🚌 CommandBus & QueryBus

Untuk menghindari tight coupling antara Controller dan Handler, digunakan mediator pattern:

* 🚌 CommandBus
* 🚌 QueryBus

### 🚌 CommandBus

Menangani operasi yang **mengubah state**.

Flow:

```text
Controller → Command → CommandBus → Handler → Repository → Database
```

Contoh:

```php
$command = new CreateUserCommand($name, $email, $password);
$this->commandBus->dispatch($command);
```

Karakteristik:

* Fokus pada perubahan data
* Tidak untuk mengambil data kompleks
* 1 Command = 1 Handler

---

### 🚌 QueryBus

Menangani operasi **read-only**.

Flow:

```text
Controller → Query → QueryBus → Handler → Read Model → Response
```

Contoh:

```php
$query = new ListUsersQuery($search, $page, $perPage);
$result = $this->queryBus->ask($query);
```

Karakteristik:

* Tidak mengubah state
* Return DTO / array / pagination
* Terpisah dari write logic

---

## 🔄 Flow CQRS

### ✍ Write Flow

1. Controller menerima request
2. Validasi via FormRequest
3. Membuat Command
4. Dispatch ke CommandBus
5. Handler memanggil Repository
6. Simpan ke database

### 📖 Read Flow

1. Controller menerima request
2. Membuat Query
3. QueryBus ask ke Handler
4. Handler ambil data
5. Return data + meta pagination

---

## 🧠 Architecture Overview

Project ini menggunakan pendekatan **Clean Architecture** dengan pembagian layer berikut:

```text
app
 ├── Domain
 │
 ├── Application
 │   ├── Shared
 │   │   └── Bus
 │   ├── User
 │   │   ├── DTOs
 │   │   ├── Commands
 │   │   └── Queries
 │   └── Product
 │       ├── DTOs
 │       ├── Commands
 │       └── Queries
 │
 ├── Infrastructure
 │   ├── Persistence
 │   │   ├── Eloquent
 │   │   │   ├── Models
 │   │   │   └── Repositories
 │   └── Providers
 │
 ├── Presentation
 │   ├── Http
 │   │   ├── Controllers
 │   │   │   ├── Api
 │   │   │   └── Web
 │   │   ├── Requests
 │   │   └── Resources
 │   ├── Routes
 │   │   ├── api.php
 │   │   └── web.php
 │   └── Views
 │
 └── Support
     └── Helpers
```

---

🚀 1) Membuat Project dari Nol
-----------------------------

[](#-1-membuat-project-dari-nol)

### 1.1 Create Laravel project

[](#11-create-laravel-project)

```
composer create-project laravel/laravel Laravel-CleanArchitecture-CQRS-Starter-Template
cd Laravel-CleanArchitecture-CQRS-Starter-Template
```

### 1.2 Setup environment

[](#12-setup-environment)

```
cp .env.example .env
php artisan key:generate
```

### 1.3 Configure database

[](#13-configure-database)

Edit `.env`, contoh MySQL:

```
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=starter_template
DB_USERNAME=root
DB_PASSWORD=
```

---

🧱 2) Membuat Struktur Clean Architecture + CQRS
-----------------------------------------------

[](#-2-membuat-struktur-clean-architecture--cqrs)

Jalankan perintah berikut untuk membuat folder layer dan module:

```
mkdir -p app/{Domain,Application,Infrastructure,Presentation,Support}

mkdir -p app/Domain/User/{Entities,Contracts}
mkdir -p app/Domain/Product/{Entities,Contracts}

mkdir -p app/Application/Shared/Bus
mkdir -p app/Application/User/{DTOs,Commands,Queries}
mkdir -p app/Application/User/Commands/{CreateUser,UpdateUser,DeleteUser}
mkdir -p app/Application/User/Queries/{GetUserById,ListUsers}

mkdir -p app/Application/Product/{DTOs,Commands,Queries}
mkdir -p app/Application/Product/Commands/{CreateProduct,UpdateProduct,DeleteProduct}
mkdir -p app/Application/Product/Queries/{GetProductById,ListProducts}

mkdir -p app/Infrastructure/Persistence/Eloquent/{Models,Repositories}
mkdir -p app/Infrastructure/Providers

mkdir -p app/Presentation/Routes
mkdir -p app/Presentation/Views/{users,products}
mkdir -p app/Presentation/Http/{Controllers,Requests,Resources}
mkdir -p app/Presentation/Http/Controllers/{Api,Web}
mkdir -p app/Presentation/Http/Requests/{User,Product}

mkdir -p app/Support/Helpers
```

---

🛣️ 3) Routing &amp; Views dari `app/Presentation`
-------------------------------------------------

[](#️-3-routing--views-dari-apppresentation)

Template ini tidak menggunakan `routes/web.php` dan `routes/api.php` default. Sebagai gantinya:

- ✅ Routes: `app/Presentation/Routes/web.php` dan `app/Presentation/Routes/api.php`
- ✅ Views: `app/Presentation/Views/...`

### 3.1 Load routes dari `app/Presentation/Routes`

[](#31-load-routes-dari-apppresentationroutes)

Edit file: `app/Providers/RouteServiceProvider.php`

Ubah method `boot()`:

```
public function boot(): void
{
    $this->routes(function () {
        \Illuminate\Support\Facades\Route::middleware('api')
            ->prefix('api')
            ->group(app_path('Presentation/Routes/api.php'));

        \Illuminate\Support\Facades\Route::middleware('web')
            ->group(app_path('Presentation/Routes/web.php'));
    });
}
```

### 3.2 Load views dari `app/Presentation/Views`

[](#32-load-views-dari-apppresentationviews)

Buat provider:

```
php artisan make:provider PresentationServiceProvider
```

Isi `app/Infrastructure/Providers/PresentationServiceProvider.php`:

```
