Skip to content

damku999/laravel-api-modules

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

πŸš€ Laravel API Modules

Latest Version on Packagist Total Downloads MIT Licensed Laravel PHP

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 filtering
  • GET /api/products/{id} - Get single product
  • POST /api/products - Create new product
  • PUT /api/products/{id} - Update product
  • DELETE /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

Resources


🀝 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

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

About

No description, website, or topics provided.

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Packages

No packages published

Languages