kalimeromk / modular-laravel-boilerplate
The skeleton application for the Laravel framework.
Installs: 10
Dependents: 0
Suggesters: 0
Security: 0
Stars: 4
Watchers: 1
Forks: 0
Open Issues: 0
Type:project
pkg:composer/kalimeromk/modular-laravel-boilerplate
Requires
- php: ^8.2
- darkaonline/l5-swagger: ^9.0
- laravel/framework: ^12
- laravel/sanctum: ^4.0
- laravel/tinker: ^2.9
- pragmarx/google2fa-laravel: ^2.3
- spatie/laravel-permission: ^6.15
Requires (Dev)
- fakerphp/faker: ^1.23
- larastan/larastan: ^3.0
- laravel/boost: ^1.0
- laravel/pail: ^1.1
- laravel/pint: ^1.13
- laravel/sail: ^1.26
- mockery/mockery: ^1.6
- nunomaduro/collision: ^8.1
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^11.0.1
- rector/rector: ^2.1.0
README
Modular Laravel Starter Kit is an advanced, API-first starter package for Laravel. It focuses on modularity and clean architecture, aiming to make API development fast, sustainable, and scalable with minimal manual intervention.
🚀 Introduction
This kit is ideal for teams and developers who want a clean, well-structured codebase with clearly separated logic, using modern patterns such as repositories, DTOs, actions, and automatic relationship mapping.
🐳 Docker Setup (Recommended)
For the best development experience, we recommend using Docker:
Quick Docker Setup
# Clone the repository git clone <repository-url> cd modular-laravel # Run Docker setup (installs dependencies, runs migrations, seeders) ./docker-setup.sh # Access the application # Web: http://localhost:8080 # API Docs: http://localhost:8080/api/documentation # Database: localhost:3306 (homestead/secret)
Docker Commands
# Run tests in Docker ./docker-test.sh # Stop containers make docker-stop # Restart containers make docker-restart # View logs make docker-logs
Manual Docker Commands
# Start containers docker-compose up -d # Run migrations docker-compose exec app php artisan migrate:fresh --seed # Run tests docker-compose exec app php artisan test # Access container docker-compose exec app bash
💻 Local Development (Alternative)
If you prefer local development without Docker:
# Clone the repository git clone <repository-url> cd modular-laravel # Install dependencies composer install # Environment setup cp .env.example .env php artisan key:generate # Database setup (requires MySQL/PostgreSQL) php artisan migrate:fresh --seed # Start development server php artisan serve
🛠️ Available Commands
This project includes a Makefile for common tasks:
# Show all available commands make help # Docker commands make docker-setup # Setup Docker environment make docker-test # Run tests in Docker make docker-stop # Stop containers make docker-restart # Restart containers make docker-logs # View logs # Development commands make test # Run PHPUnit tests make phpstan # Run PHPStan static analysis make pint # Run Laravel Pint formatting make migrate # Run migrations make seed # Run seeders make setup # Quick local setup make clean # Clean cache # Database optimization php artisan db:optimize # Analyze database performance php artisan db:optimize --monitor # Monitor queries in real-time php artisan db:optimize --connection-info # Get connection information
🎯 Goals
- ✅ Automatic generation of complete API modules
- ✅ Minimal manual configuration
- ✅ Scalable and maintainable code
- ✅ Clear separation of concerns through modules
- ✅ No web UI or Blade support – API only
- ✅ Production-ready security with 2FA
- ✅ Optimized database performance
- ✅ Clean Architecture implementation
- ✅ Comprehensive test coverage
🔧 Features
- Modular structure: Each module is self-contained under
app/Modules - Powerful CLI Generator: Create complete modules via
php artisan make:module - Dynamic field handling: Fillables, casts, and relationships auto-handled
- Built-in Rate Limiting: Auto-generated routes include Laravel throttle middleware
- Flexible flags:
--exceptions: Generate exception classes--observers: Generate observer stubs--policies: Generate policy stubs
- Auto-discovery: Routes, migrations, factories, observers, and policies
- Repository pattern: Interface-to-implementation binding out-of-the-box
- Fully configurable:
config/modules.phpfor structure and behaviors - Two-Factor Authentication: Complete 2FA support with Google Authenticator
- Database Optimization: Performance indexes, query caching, and monitoring
- Clean Architecture: Application/Infrastructure layer separation
- Comprehensive Testing: Unit, Feature, Integration, and Performance tests
✅ Supported Field Types
| Laravel Type | SQL Equivalent | Description |
|---|---|---|
string |
VARCHAR | Short text string |
char |
CHAR | Fixed-length string |
text |
TEXT | Long text |
mediumText |
MEDIUMTEXT | Medium-length text |
longText |
LONGTEXT | Very long text |
integer |
INT | Standard integer |
tinyInteger |
TINYINT | Very small integer |
smallInteger |
SMALLINT | Small integer |
mediumInteger |
MEDIUMINT | Medium-sized integer |
bigInteger |
BIGINT | Large integer |
unsignedBigInteger |
BIGINT UNSIGNED | Large unsigned integer |
foreign |
INT (FK) | Foreign key (auto handled) |
float |
FLOAT | Floating point number |
double |
DOUBLE | Double-precision number |
decimal |
DECIMAL(8,2) | Fixed precision decimal |
boolean |
TINYINT(1) | Boolean (true/false) |
enum |
ENUM(...) | Fixed set of values |
date |
DATE | Date only |
datetime |
DATETIME | Date and time |
timestamp |
TIMESTAMP | Timestamp |
time |
TIME | Time only |
year |
YEAR | Year only |
json |
JSON | Structured JSON data |
array |
JSON (casted) | PHP array via JSON cast |
uuid |
CHAR(36) | UUID |
ipAddress |
VARCHAR(45) | IPv4/IPv6 |
macAddress |
VARCHAR(17) | MAC address |
binary |
BLOB | Binary large object |
🏗️ Clean Architecture Structure
This starter kit follows Clean Architecture principles with clear separation between Application and Infrastructure layers:
📁 Module Structure
Each module is organized into two main layers:
🎯 Application Layer (Application/)
Contains business logic and use cases:
- Actions/ - Business use cases and operations
- DTOs/ - Data Transfer Objects for API communication
- Services/ - Business services and interfaces
- Interfaces/ - Contracts for external dependencies
🔧 Infrastructure Layer (Infrastructure/)
Contains external concerns and implementations:
- Models/ - Eloquent models and database entities
- Repositories/ - Data access implementations
- Http/ - Web layer (Controllers, Requests, Resources)
- Providers/ - Service providers for dependency injection
- Routes/ - API route definitions
🔄 Dependency Flow
Controllers → Actions → Services → Repositories → Models
↓ ↓ ↓ ↓
HTTP Business Business Database
Layer Logic Services Access
- Controllers handle HTTP requests and delegate to Actions
- Actions contain business logic and orchestrate Services
- Services implement business rules and use Repositories
- Repositories abstract data access and work with Models
- Models represent database entities and relationships
🔄 Automatic Relationship Sync
You can use the SyncRelations::execute() helper to automatically sync both belongsToMany and belongsTo relationships using your DTO:
SyncRelations::execute($model, [ 'tags' => $dto->tags, // BelongsToMany 'brand' => $dto->brand_id, // BelongsTo ]);
- For
BelongsToMany, it performs$relation->sync(array) - For
BelongsTo, it sets the foreign key and saves the model if changed.
⚙️ Usage
1. Generate a New Module
php artisan make:module Product \ --model="name:string,price:float,stock:int,is_active:bool,category_id:int" \ --relations="category:belongsTo:Category,reviews:hasMany:Review" \ --exceptions \ --observers \ --policies
2. Flags
| Flag | Description |
|---|---|
--model |
Define fields and types for the model |
--relations |
Add Eloquent relationships |
--exceptions |
Generate Exceptions |
--observers |
Generate Observers and auto-register |
--policies |
Generate Policies and auto-register |
3. Structure
app/Modules/Example/
├── Application/
│ ├── Actions/
│ ├── DTOs/
│ ├── Services/
│ └── Interfaces/
├── Infrastructure/
│ ├── Models/
│ ├── Repositories/
│ ├── Http/
│ │ ├── Controllers/
│ │ ├── Requests/
│ │ └── Resources/
│ ├── Providers/
│ └── Routes/
│ └── api.php
├── Exceptions/
├── Observers/
├── Policies/
└── database/
├── migrations/
└── factories/
4. Auto-Registration
Observers and Policies are auto-registered if files exist.
5. Validation for Foreign Keys
If a field ends in _id, the generated FormRequest will contain:
'user_id' => ['required', 'integer', 'exists:users,id'],
🔗 Polymorphic Relationships
The module generator now supports polymorphic relationships for flexible data modeling.
📋 Polymorphic Relationship Types
| Type | Description | Usage |
|---|---|---|
morphTo |
Polymorphic belongs-to relationship | owner:morphTo |
morphOne |
Polymorphic one-to-one relationship | profile:morphOne:Profile:ownable |
morphMany |
Polymorphic one-to-many relationship | comments:morphMany:Comment:commentable |
morphToMany |
Polymorphic many-to-many relationship | tags:morphToMany:Tag:taggable |
💡 Module Generation Examples
1. Comments that can belong to different models
# Generate a Comment model that can be attached to any model php artisan make:module Comment \ --model="content:text,author_name:string" \ --relations="commentable:morphTo,user:belongsTo:User"
This will generate a model with commentable_type and commentable_id fields for the polymorphic relationship.
2. Product with polymorphic relationships
# Generate Product model with comments and tags php artisan make:module Product \ --model="name:string,price:float,description:text" \ --relations="comments:morphMany:Comment:commentable,tags:morphToMany:Tag:taggable"
3. Tags that can be applied to different models
# Generate Tag model for polymorphic many-to-many relationship php artisan make:module Tag \ --model="name:string,slug:string,color:string" \ --relations="products:morphedByMany:Product:taggable,posts:morphedByMany:Post:taggable"
4. Images/attachments that can belong to different entities
# Generate Attachment model php artisan make:module Attachment \ --model="filename:string,path:string,size:integer,mime_type:string" \ --relations="attachable:morphTo,user:belongsTo:User"
🎯 YAML Configuration for Polymorphic Relationships
modules: # Comment that can be attached to any model Comment: fields: content: text author_name: string rating: integer relations: commentable: morphTo user: belongsTo:User observers: true # Product with polymorphic relationships Product: fields: name: string price: float description: text is_active: boolean relations: # Standard relationships category: belongsTo:Category # Polymorphic relationships comments: morphMany:Comment:commentable tags: morphToMany:Tag:taggable attachments: morphMany:Attachment:attachable policies: true # Tags for polymorphic many-to-many Tag: fields: name: string slug: string color: string relations: # Can be applied to different models products: morphedByMany:Product:taggable posts: morphedByMany:Post:taggable # Attachments that can belong to different models Attachment: fields: filename: string path: string size: integer mime_type: string relations: attachable: morphTo user: belongsTo:User
🔧 Automatic Syncing of Polymorphic Relationships
The SyncRelations class supports automatic syncing of polymorphic relationships:
use App\Modules\Core\Support\Relations\SyncRelations; // In your controller or action SyncRelations::execute($model, [ 'tags' => $dto->tag_ids, // MorphToMany - sync with IDs 'commentable' => $product, // MorphTo - with model instance 'owner' => [ // MorphTo - with type and id 'type' => 'App\\Models\\User', 'id' => 123 ], 'category' => $dto->category_id, // Standard belongsTo relationship ]);
Supported Relationship Types:
MorphToMany: Usessync()for polymorphic many-to-manyMorphTo: Automatically setstypeandidfields- Accepts model instances:
$user - Accepts arrays:
['type' => 'App\\Models\\User', 'id' => 123] - Accepts
nullto clear the relationship
- Accepts model instances:
🌟 Benefits of Polymorphic Relationships
- Flexibility - One model can connect to different types
- DRY Principle - Avoid duplicating tables for similar relationships
- Scalability - Easy to add new models without changing existing ones
- Elegance - Cleaner solution for complex relationships
📚 Practical Usage Examples
Comment System:
// Comment on a product $comment->commentable()->associate($product); // Comment on a blog post $comment->commentable()->associate($blogPost); // Get comments for a product $productComments = $product->comments;
Tagging System:
// Add tags to a product $product->tags()->attach([1, 2, 3]); // Get all products with a specific tag $taggedProducts = $tag->products;
📦 Module Generation via YAML
In addition to the php artisan make:module command, you can now generate multiple modules at once using a YAML configuration file.
🔧 Usage
- Create a
modules.yamlfile in the root of your project:
modules: Product: fields: name: string price: float is_active: boolean relations: belongsToMany: [Category] user: belongsTo:User observers: true policies: true Category: fields: name: string relations: belongsToMany: [Product]
- Run the command:
php artisan modules:build-from-yaml
This will:
📌 Note: Pivot migrations are automatically generated only when using
modules:build-from-yamland when both related modules define abelongsToManyrelationship to each other.
- Automatically generate all modules using the same logic as
make:module - Parse
fields,relations, and options likeobserversandpolicies - Fill in
fillable,casts,migrations,factories, andresources - Avoids manual repetition by letting you define multiple modules at once
🔐 Two-Factor Authentication (2FA)
The starter kit includes comprehensive Two-Factor Authentication support using Google Authenticator (TOTP).
🚀 2FA Features
- TOTP Support - Time-based One-Time Password using Google Authenticator
- QR Code Generation - Automatic QR code for easy setup
- Recovery Codes - 8 single-use recovery codes for account recovery
- Secure Storage - Encrypted secret keys and recovery codes
- API Endpoints - Complete REST API for 2FA management
📋 2FA API Endpoints
| Method | Endpoint | Description | Rate Limit |
|---|---|---|---|
GET |
/api/v1/auth/2fa/status |
Get 2FA status | 120/min |
POST |
/api/v1/auth/2fa/setup |
Generate secret & QR code | 3/hour |
POST |
/api/v1/auth/2fa/verify |
Verify code & enable 2FA | 10/min |
DELETE |
/api/v1/auth/2fa/disable |
Disable 2FA | 3/hour |
POST |
/api/v1/auth/2fa/recovery-codes |
Generate new recovery codes | 3/hour |
💡 Usage Examples
Setup 2FA
# Get 2FA setup data curl -X POST http://localhost:8080/api/v1/auth/2fa/setup \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json"
Verify 2FA Code
# Verify with TOTP code curl -X POST http://localhost:8080/api/v1/auth/2fa/verify \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{"code": "123456"}' # Verify with recovery code curl -X POST http://localhost:8080/api/v1/auth/2fa/verify \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{"recovery_code": "abcd1234ef"}'
🗄️ Database Optimization
The starter kit includes comprehensive database optimization features for production-ready performance.
⚡ Database Optimization Features
- Performance Indexes - Automatically added to all database tables
- Query Caching - Intelligent caching with TTL support
- Query Monitoring - Real-time query performance tracking
- Slow Query Detection - Automatic identification of performance bottlenecks
- Batch Operations - Optimized bulk insert/update operations
- Cursor Pagination - Efficient pagination for large datasets
- Database Analysis - Table size and performance analysis
🛠️ Database Optimization Commands
# Analyze database tables and performance php artisan db:optimize # Monitor queries in real-time (30 seconds) php artisan db:optimize --monitor --duration=30 # Get database connection information php artisan db:optimize --connection-info # Analyze specific table php artisan db:optimize --table=users
📊 Database Indexes Added
Users Table:
email_verified_at- Email verification queriescreated_at- User creation date queriesupdated_at- User update date queries
Sessions Table:
ip_address- IP-based session queriesuser_id + last_activity- User session activity queries
Personal Access Tokens:
last_used_at- Token usage queriesexpires_at- Token expiration querieslast_used_at + expires_at- Token cleanup queries
Permission Tables:
guard_name- Guard-based permission queriescreated_at- Permission creation queriesupdated_at- Permission update queries
2FA Columns:
two_factor_confirmed_at- 2FA status queries
🔧 Query Optimization Features
- Conditional Eager Loading - Prevents N+1 query problems
- Cache Pattern Invalidation - Automatic cache cleanup
- Query Performance Monitoring - Track slow queries
- Database Connection Optimization - Optimized connection settings
- Batch Insert/Update - Efficient bulk operations
🧩 Planned Features
- Event and Listener support
- Notification scaffolding
- Relationship sync logic from DTO
- Sanctum authentication integration
- Exception handling stubs per action
- Resource, DTO, Request,Action,Controller
- Feature test generation
- Migration and Factory generators
- Add Yaml support for module generation
- Two-Factor Authentication (2FA) support
- Database optimization and performance monitoring
- Interactive CLI wizard (make:module step-by-step)
✅ Requirements
- PHP 8.3+
- Laravel 12+
- MySQL 8.0+ / PostgreSQL 13+ / SQLite 3.35+
- Composer 2.0+
- Docker & Docker Compose (for Docker setup)
💡 Notes
- API-only – no Blade views or web routes.
- Ideal for headless frontends (React, Vue, etc.)
- Production-ready with comprehensive security and performance optimizations
- Clean Architecture ensures maintainable and testable code
- Database optimization provides enterprise-level performance
- Two-Factor Authentication enhances security for sensitive applications
🤝 Contribution
- Issues and feature requests welcome.
- Pull Requests encouraged.
🐳 Docker Support
This starter kit includes full support for Docker. You can spin up the app, database, and web server with a single command.
✅ Getting Started
-
Build and start containers:
docker compose up -d --build
-
Stop containers:
docker compose down
-
Access Laravel container (for running artisan/test/composer):
docker exec -it app_module bash -
Run migrations:
docker exec -it app_module php artisan migrate -
Run tests:
docker exec -it app_module php artisan test
-
MySQL connection (host machine):
- Host:
127.0.0.1 - Port:
3306 - User:
homestead - Password:
secret - Database:
homestead
- Access the application:
- Web:
http://localhost:8080 - API Documentation:
http://localhost:8080/api/documentation - Health Check:
http://localhost:8080/api/health