seangly/laravel-csrm

One command to scaffold a full Controller-Service-Repository-Model design pattern in Laravel

Maintainers

Package info

github.com/Chhounseangly/laravel-csrm

pkg:composer/seangly/laravel-csrm

Statistics

Installs: 2

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

1.0.0 2026-05-05 10:32 UTC

This package is auto-updated.

Last update: 2026-06-01 04:45:20 UTC


README

Overview

The Laravel CSRM Package is a powerful generator that scaffolds a complete Controller-Service-Repository-Model design pattern in your Laravel application. It follows SOLID principles and best practices for enterprise-level Laravel development.

Requirements

  • PHP: 8.1 or higher
  • Laravel: 10.x, 11.x, or 12.x
  • Composer: Latest version

Installation

Step 1: Install the Package via Composer

Option A: From Packagist (Production)

composer require seangly/laravel-csrm

Option B: From Local Path (Local Development)

If you have the package code locally and want to test it:

  1. Add the path repository to your composer.json:
{
    "repositories": [
        {
            "type": "path",
            "url": "../laravel-csrm",
            "options": {
                "symlink": true
            }
        }
    ],
    "require": {
        "seangly/laravel-csrm": "^1.0@dev"
    }
}
  1. Then run:
composer install

Note: Don't use composer require when a path repository is configured. Instead, manually add the package to require section and run composer install or composer update.

The package will be automatically discovered and registered through Laravel's auto-discovery feature.

Step 2: Verify Installation

Check that the CSRM commands are available:

php artisan list | grep csrm

You should see:

  csrm:install              Install base CSRM classes (Controller, Service, Repository)
  csrm:make                 Generate a new CSRM module (Controller, Service, Repository, Model, Migration)

Usage

Initial Setup

Before creating modules, set up the base CSRM structure:

php artisan csrm:install

This command generates:

  • BaseController - Base controller class
  • BaseService - Base service class
  • BaseRepository - Base repository class
  • BaseRepositoryInterface - Repository interface contract

No example module is generated by default. Use php artisan csrm:make {Name} to create actual modules.

Options

php artisan csrm:install --force

The --force flag overwrites existing files without prompting.

Generate New Modules

After initial setup, create new CSRM modules:

php artisan csrm:make {name}

Example

php artisan csrm:make Post

This generates the CSRM module for a Post:

  • app/Models/Post.php - Eloquent model
  • database/migrations/*_create_posts_table.php - Database migration
  • app/Repositories/PostRepository.php - Repository for data operations
  • app/Repositories/Contracts/PostRepositoryInterface.php - Repository interface
  • app/Services/PostService.php - Business logic service
  • app/Http/Controllers/PostController.php - Web controller (default, generated with empty method bodies)

Controller Mode Options

You can generate controller variants:

# Web controller (default)
php artisan csrm:make Product --only=controller

# API controller
php artisan csrm:make Product --only=controller --api
  • --api creates app/Http/Controllers/Api/*Controller.php
  • without --api, controller is generated in app/Http/Controllers/*Controller.php (web default)
  • By default, generated controller methods are empty and do not include repository/service scaffolding
  • If both --api and --web are provided together, the command fails and asks you to choose one.

Selective Generation

Generate only specific components:

php artisan csrm:make Product --only=model,migration,repository

Available Options

  • model - Eloquent model (implemented)
  • migration - Database migration (implemented)
  • repository - Repository class (implemented)
  • service - Service class (implemented)
  • controller - HTTP controller (implemented)

Current Generator Status

Currently implemented:

  • model
  • migration
  • repository
  • service
  • controller

Overwrite Existing Files

php artisan csrm:make Order --force

Directory Structure

After running csrm:install, your application structure will be:

app/
├── Http/
│   ├── Controllers/
│   │   ├── BaseController.php
│   │   ├── UserController.php
│   │   └── ...
├── Models/
│   ├── User.php
│   └── ...
├── database/
│   └── migrations/
│       └── *_create_users_table.php
├── Repositories/
│   ├── Contracts/
│   │   ├── BaseRepositoryInterface.php
│   │   ├── UserRepositoryInterface.php
│   │   └── ...
│   ├── BaseRepository.php
│   ├── UserRepository.php
│   └── ...
├── Services/
│   ├── BaseService.php
│   ├── UserService.php
│   └── ...
└── Providers/
    └── AppServiceProvider.php (updated with repository bindings)

Design Pattern Explanation

Repository Layer (Data Access)

Handles data access, including queries and persistence operations.

// Read operations
$user = $repository->find(1);
$users = $repository->all();
$users = $repository->paginate(15);
$user = $repository->findBy('email', 'user@example.com');

// Write operations
$created = $repository->create($data);
$updated = $repository->update($id, $data);
$deleted = $repository->delete($id);

BaseRepositoryInterface methods:

  • all() - Get all records
  • paginate() - Paginate records
  • find() - Find by ID
  • findOrFail() - Find by ID or throw exception
  • query() - Get query builder for complex queries
  • findBy() - Find by field and value
  • findAllBy() - Find all by field and value
  • create() - Create new record
  • update() - Update existing record
  • delete() - Delete record

Service Layer (Business Logic & Actions)

Handles business logic and orchestrates action flows. It calls repository methods for persistence.

public function create(array $data): User
{
    // Add validation, transformation, logging, etc.
    return $this->repository->create($data);
}

public function update(int $id, array $data): User
{
    // Add business logic before/after update
    return $this->repository->update($id, $data);
}

public function delete(int $id): bool
{
    // Add cleanup, cascading operations, etc.
    return $this->repository->delete($id);
}

Architecture Summary

┌─────────────────────────────────────────────────────────────────┐
│                    BaseRepositoryInterface                      │
│  ┌─────────────────────────────────────────────────────────────┐ │
│  │  Query Methods: all(), find(), paginate(), query()         │ │
│  │  Data Actions: create(), update(), delete()                │ │
│  └─────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
                                   │
                                   │ implements
                                   ▼
┌─────────────────────────────────────────────────────────────────┐
│                     BaseRepository                              │
│  ┌─────────────────────────────────────────────────────────────┐ │
│  │  ✅ Query Methods: IMPLEMENTED                              │ │
│  │  ✅ Data Actions: IMPLEMENTED                               │ │
│  └─────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
                                   │
                                   │ injected into
                                   ▼
┌─────────────────────────────────────────────────────────────────┐
│                      BaseService                                 │
│  ┌─────────────────────────────────────────────────────────────┐ │
│  │  ✅ Business Actions: create(), update(), delete()          │ │
│  │  ✅ Orchestrates and delegates persistence to repository    │ │
│  └─────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘

Configuration

Publishing Assets

To customize stubs, publish them to your project:

php artisan vendor:publish --tag=csrm-stubs

Customized stubs will be placed in stubs/csrm/ and will be used for future generation.

Repository Binding

The package automatically binds repositories in AppServiceProvider:

$this->app->bind(
    \App\Repositories\Contracts\UserRepositoryInterface::class,
    \App\Repositories\UserRepository::class,
);

You can inject the interface in your service or controller:

public function __construct(UserRepositoryInterface $repository)
{
    $this->repository = $repository;
}

Next Steps

1. Run Database Migrations

After installation or creating new modules:

php artisan migrate

2. Add Routes Manually

The package does not auto-generate route files for new modules. Add routes manually as needed, for example:

use App\Http\Controllers\Api\ArticleController;

Route::apiResource('articles', ArticleController::class);

3. Customize Generated Code

The generated files are starting points. Customize them for your specific business logic:

  • Add additional methods to repositories
  • Implement complex business logic in services
  • Implement relationships in models

Common Workflows

Create a Complete Module

# 1. Generate the module
php artisan csrm:make Article

# 2. Add routes
# 3. Run migrations (after creating your migration)
# 4. Test the endpoints
curl http://localhost:8000/api/articles

Add Additional Functionality

After generating a module, enhance the service layer:

// app/Services/ArticleService.php
public function publishArticles()
{
    return $this->repository->query()->whereNotNull('published_at')->get();
}

public function archiveOldArticles($months = 12)
{
    return $this->repository->where(
        'created_at', '<', now()->subMonths($months)
    )->delete();
}

Use Repository Interface in Multiple Services

// app/Services/ArticleStatisticsService.php
public function __construct(
    ArticleRepositoryInterface $repository,
    UserRepositoryInterface $userRepository
)
{
    $this->repository = $repository;
    $this->userRepository = $userRepository;
}

Troubleshooting

Commands Not Showing

Verify the package is installed:

composer show seangly/laravel-csrm

Clear cached services:

php artisan cache:clear
php artisan config:cache

Regenerate autoloaders:

composer dump-autoload

Migration Errors

Ensure your database is properly configured in .env:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=root
DB_PASSWORD=

Class Not Found Errors

Clear application cache:

php artisan optimize:clear

Contributing & Support

For issues, feature requests, or contributions, visit the GitHub repository:

https://github.com/Chhounseangly/laravel-csrm

License

This package is licensed under the MIT license. See the LICENSE file for details.

Quick Reference

Installation

# Option 1: Install from Packagist (Production)
composer require seangly/laravel-csrm

# Option 2: Install from local path (Development)
# 1. Add to composer.json repositories and require sections (see Installation section)
# 2. Then run:
composer install

Common Commands

# Initialize base CSRM classes
php artisan csrm:install

# Generate new module
php artisan csrm:make Post

# Generate web controller (default)
php artisan csrm:make Product --only=controller

# Generate API controller
php artisan csrm:make Product --only=controller --api

# Generate specific components only
php artisan csrm:make Product --only=model,migration,repository

# Force overwrite existing files
php artisan csrm:make Order --force

# Run migrations
php artisan migrate