webmonks / laravel-api-modules
SOLID principle, modular API code generator for Laravel
Requires
- php: >=7.4
- barryvdh/laravel-dompdf: ^2.0 || ^3.0
- illuminate/support: ^8.0|^9.0|^10.0|^11.0
- twilio/sdk: ^6.0|^7.0|^8.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- larastan/larastan: ^1.0|^2.0|^3.0
- laravel/framework: ^8.0|^9.0|^10.0|^11.0
- mockery/mockery: ^1.4
- orchestra/testbench: ^6.0|^7.0|^8.0|^9.0
- pestphp/pest: ^1.23|^2.0|^3.0
- pestphp/pest-plugin-laravel: ^1.4|^2.0|^3.0
- symfony/var-dumper: ^5.0|^6.0|^7.0
- vimeo/psalm: ^5.0|^6.0
README
A powerful SOLID-principle Laravel modular code generator specifically designed for API-first projects.
Transform your Laravel development with intelligent module generation that creates clean, maintainable, and scalable API architectures following industry best practices.
โจ Why Laravel API Modules?
๐ฏ Built for API Excellence
- Zero Frontend Concerns: Pure API-focused architecture
- SOLID Principles: Every generated component follows dependency injection and single responsibility
- Repository Pattern: Clean separation of data access logic
- Service Layer: Business logic abstraction for better testability
โก Intelligent Generation
- Complete Module Scaffold: Controllers, Models, Services, Repositories, Interfaces, Requests, Migrations, Tests
- Two Generation Modes: Simple list APIs or full CRUD resources
- Auto-Wired Dependencies: Everything is pre-configured and ready to use
- Smart Naming: Consistent naming conventions across all components
๐ง Developer Experience
- One Command Setup: Generate complete modules with a single artisan command
- Zero Configuration: Works out of the box with sensible defaults
- Full Customization: Publish and modify all templates to match your standards
- IDE Friendly: Proper type hints and interfaces for better development experience
๐ฆ Installation
Requirements
Component | Version |
---|---|
PHP | ^7.4 | ^8.0 | ^8.1 | ^8.2 | ^8.3 |
Laravel | ^8.0 | ^9.0 | ^10.0 | ^11.0 | ^12.0 |
Quick Install
# Install the package
composer require webmonks/laravel-api-modules
Configuration (Optional)
# Publish configuration for customization php artisan vendor:publish --tag=laravel-api-modules-config # Publish stub templates for team-specific modifications php artisan vendor:publish --tag=laravel-api-modules-stubs
That's it! The package is auto-discovered and ready to use. ๐
๐ Quick Start
Generate Your First Module
# Create a simple list-only API module php artisan make:module Blog # Create a full CRUD resource module php artisan make:module Product --resource
Remove Modules Safely
# Preview what would be removed (dry-run) php artisan remove:module Blog --preview # Remove with interactive confirmation php artisan remove:module Blog # Remove with automatic backup (default) php artisan remove:module Product # Remove without confirmations php artisan remove:module Product --force # Remove without creating backup php artisan remove:module Product --force --no-backup
What Gets Generated?
Simple Module (php artisan make:module Blog
)
app/Modules/Blog/
โโโ Controllers/BlogController.php # List endpoint only
โโโ Models/Blog.php # Eloquent model with traits
โโโ Services/BlogService.php # Business logic layer
โโโ Repositories/BlogRepository.php # Data access layer
โโโ Request/ListBlogRequest.php # Validation for list endpoint
โโโ routes.php # Auto-registered routes
app/Core/
โโโ Interfaces/BlogRepositoryInterface.php # Repository contract
โโโ Providers/RepositoryServiceProvider.php # Auto-generated bindings
database/migrations/
โโโ xxxx_xx_xx_xxxxxx_create_blogs_table.php
tests/
โโโ Feature/Modules/Blog/BlogFeatureTest.php
โโโ Unit/Modules/Blog/BlogUnitTest.php
Resource Module (php artisan make:module Product --resource
)
app/Modules/Product/
โโโ Controllers/ProductController.php # Full CRUD endpoints
โโโ Models/Product.php # Eloquent model
โโโ Services/ProductService.php # Complete business logic
โโโ Repositories/ProductRepository.php # Full data operations
โโโ Request/
โ โโโ ListProductRequest.php # List validation
โ โโโ ViewProductRequest.php # View validation
โ โโโ CreateProductRequest.php # Create validation
โ โโโ UpdateProductRequest.php # Update validation
โ โโโ DeleteProductRequest.php # Delete validation
โโโ routes.php # All CRUD routes
Your Project Structure
After generating your first module, your Laravel application will have this enhanced structure:
app/
โโโ Core/ # ๐๏ธ Architecture Layer
โ โโโ Interfaces/ # Repository contracts
โ โ โโโ BlogRepositoryInterface.php
โ โโโ Providers/ # Auto-generated service bindings
โ โ โโโ RepositoryServiceProvider.php
โ โโโ Services/ # Shared base services
โ โ โโโ BaseService.php
โ โโโ Traits/ # Reusable functionality
โ โโโ ApiResponser.php # Standard API responses
โ โโโ ActivityLogHelper.php # Model activity tracking
โ โโโ PdfGeneratorTrait.php # PDF generation
โ โโโ SmsSender.php # SMS notifications
โ โโโ UserUpdater.php # Auto user tracking
โโโ Helpers/ # ๐ง Utility Functions
โ โโโ AutoloadFiles/ # Auto-loaded helpers
โ โโโ string_helpers.php
โโโ Models/ # ๐๏ธ Shared Models
โ โโโ BaseModel.php # Enhanced base model
โโโ Modules/ # ๐ฏ Your API Modules
โโโ Blog/
โโโ Controllers/BlogController.php
โโโ Models/Blog.php
โโโ Repositories/BlogRepository.php
โโโ Services/BlogService.php
โโโ Request/ListBlogRequest.php
โโโ routes.php # Auto-discovered routes
config/
โโโ laravel-api-modules.php # Package configuration
database/migrations/
โโโ 2024_01_01_000000_create_blogs_table.php
tests/
โโโ Feature/Modules/Blog/BlogFeatureTest.php
โโโ Unit/Modules/Blog/BlogUnitTest.php
๐ง Core Features
๐๏ธ Safe Module Removal
Complete cleanup with safety checks! The package provides:
- ๐ Preview Mode: See exactly what files will be removed before deletion
- ๐ฆ Automatic Backup: Creates timestamped backups before removal (optional)
- โ ๏ธ Multi-stage Confirmations: Multiple safety prompts prevent accidental deletion
- ๐งน Complete Cleanup: Removes all related files (controllers, models, tests, migrations, interfaces)
- ๐ Repository Binding Cleanup: Automatically cleans up service provider bindings
- ๐จ Security Validation: Prevents path traversal and validates module names
# Safe removal with all protections php artisan remove:module UserProfile # Quick preview of what would be removed php artisan remove:module UserProfile --preview # Force removal without confirmations php artisan remove:module UserProfile --force --no-backup
๐ Automatic Repository Binding
Zero Configuration Required! The package automatically:
- Generates
RepositoryServiceProvider.php
to bind interfaces to implementations - Registers the provider in Laravel's service container
- Creates proper dependency injection for all your modules
// This happens automatically - no manual binding needed! $this->app->bind( BlogRepositoryInterface::class, BlogRepository::class );
๐ท๏ธ Smart Traits System
The package includes battle-tested traits for common API functionality:
Trait | Purpose | Auto-Included |
---|---|---|
ApiResponser |
Consistent API response format | โ Required |
ActivityLogHelper |
Track model changes and actions | โ๏ธ Optional |
PdfGeneratorTrait |
Generate PDFs from Blade templates | โ๏ธ Optional |
SmsSender |
Send SMS via Twilio with logging | โ๏ธ Optional |
UserUpdater |
Auto-manage created_by , updated_by fields |
โ๏ธ Optional |
๐ Helper Autoloader
Drop any PHP helper files into app/Helpers/AutoloadFiles/
and they're automatically available throughout your application:
// app/Helpers/AutoloadFiles/api_helpers.php function transform_response($data, $message = 'Success') { return ['data' => $data, 'message' => $message]; } // Available everywhere in your app automatically! return transform_response($users, 'Users retrieved successfully');
โ๏ธ Configuration
The package works perfectly with zero configuration, but offers extensive customization options:
๐ View Configuration Options
// config/laravel-api-modules.php return [ // Directory Structure 'modules_dir' => 'app/Modules', 'core_interfaces_dir' => 'app/Core/Interfaces', // Namespaces 'namespace' => 'App\\Modules', 'interface_namespace' => 'App\\Core\\Interfaces', // Base Classes 'enable_base_model' => true, // Generate BaseModel 'enable_base_service' => true, // Generate BaseService 'model_extends_base' => 'BaseModel', // Code Generation 'generate_migration' => true, // Create migrations 'generate_tests' => true, // Create test files 'auto_discover_routes' => true, // Auto-register routes // Traits Configuration 'base_model_traits' => [ 'ApiResponser' => true, // Required 'ActivityLogHelper' => true, // Optional 'PdfGeneratorTrait' => true, // Optional 'SmsSender' => true, // Optional 'UserUpdater' => true, // Optional ], ];
๐ก Usage Examples
Example 1: Blog API Module
# Generate a simple blog list API php artisan make:module Blog # Remove the blog module safely (with backup) php artisan remove:module Blog
Generated controller will have a clean, testable structure:
// app/Modules/Blog/Controllers/BlogController.php class BlogController extends Controller { protected $blogService; public function __construct(BlogService $blogService) { $this->blogService = $blogService; // Auto-injected } public function list(ListBlogRequest $request) { $response = $this->blogService->listBlogs($request->validated()); return $this->successResponse( $response, 'Blogs retrieved successfully', Response::HTTP_OK ); } }
Example 2: Full CRUD Product API
# Generate a complete product management API php artisan make:module Product --resource # Preview what would be removed before deletion php artisan remove:module Product --preview # Remove with force (skip confirmations) php artisan remove:module Product --force
This creates a full API with endpoints:
GET /api/products
- List products with filteringGET /api/products/{id}
- Get single productPOST /api/products
- Create new productPUT /api/products/{id}
- Update productDELETE /api/products/{id}
- Delete product
Example 3: Custom Helper Integration
// app/Helpers/AutoloadFiles/product_helpers.php function calculate_discount($original_price, $discount_percent) { return $original_price * (1 - $discount_percent / 100); } function format_currency($amount) { return '$' . number_format($amount, 2); }
// Use anywhere in your application $discounted_price = calculate_discount($product->price, 15); $formatted_price = format_currency($discounted_price);
๐ง Advanced Customization
Custom Stub Templates
Publish stubs and modify them to match your team's conventions:
php artisan vendor:publish --tag=laravel-api-modules-stubs
Edit any stub in stubs/laravel-api-modules/
to customize generated code:
// stubs/laravel-api-modules/controller.stub class {{model}}Controller extends Controller { // Your custom controller template // Add your standard methods, middleware, etc. }
Extending Base Classes
The generated BaseModel
and BaseService
can be extended with your common functionality:
// app/Models/BaseModel.php - Auto-generated, customize as needed abstract class BaseModel extends Model { use ApiResponser, ActivityLogHelper, UserUpdater; // Add your common model methods here public function scopeActive($query) { return $query->where('is_active', true); } }
๐งช Testing
The package generates comprehensive test files for each module:
// tests/Feature/Modules/Blog/BlogFeatureTest.php class BlogFeatureTest extends TestCase { public function test_can_list_blogs() { $response = $this->getJson('/api/blogs'); $response->assertStatus(200) ->assertJsonStructure(['data', 'message']); } }
Run tests for your modules:
# Run all tests php artisan test # Run specific module tests php artisan test tests/Feature/Modules/Blog/ php artisan test tests/Unit/Modules/Blog/
๐ Documentation
Complete Guides
- ๐ Directory Structure Deep Dive - Understand the generated architecture
- ๐ง Helper System Guide - Master the auto-loader and create custom helpers
- ๐ท๏ธ Traits Reference - Leverage built-in traits and create your own
- โ๏ธ Configuration Reference - Customize every aspect of generation
- ๐ Migration Guide - Upgrade between versions smoothly
Resources
- ๐ Changelog - Track all changes and improvements
- ๐ค Contributing Guidelines - Join our development community
- ๐ Security Policy - Report security vulnerabilities
- โ๏ธ Code of Conduct - Community standards
๐ค Contributing
We welcome contributions from the community! Whether it's:
- ๐ Bug Reports: Found an issue? Let us know!
- ๐ก Feature Requests: Have ideas for improvements?
- ๐ง Code Contributions: Submit pull requests with enhancements
- ๐ Documentation: Help improve our guides and examples
See our Contributing Guidelines for details.
๐ Credits
Laravel API Modules is crafted with โค๏ธ by WebMonks Technologies
- Lead Developer: Darshan Baraiya
- Company: WebMonks Technologies
Built With
- Laravel - The PHP Framework for Web Artisans
- PHP - A popular general-purpose scripting language
- SOLID Principles - Object-oriented design principles
- Repository Pattern - Clean architecture pattern
๐ License
This package is open-sourced software licensed under the MIT License.
๐ Star this repository if it helped you!
Made with โค๏ธ for the Laravel community
โญ Give us a star โข ๐ฆ View on Packagist โข ๐ Report Issues