PHPackages                             seangly/laravel-csrm - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. seangly/laravel-csrm

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

seangly/laravel-csrm
====================

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

v1.1.0(4w ago)05MITPHPPHP &gt;=8.1

Since May 5Pushed 4w agoCompare

[ Source](https://github.com/Chhounseangly/laravel-csrm)[ Packagist](https://packagist.org/packages/seangly/laravel-csrm)[ RSS](/packages/seangly-laravel-csrm/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependencies (12)Versions (3)Used By (0)

Laravel CSRM Package - Setup Guide
==================================

[](#laravel-csrm-package---setup-guide)

Overview
--------

[](#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
------------

[](#requirements)

- **PHP**: 8.1 or higher
- **Laravel**: 10.x or higher
- **Composer**: Latest version

Installation
------------

[](#installation)

### Step 1: Install the Package via Composer

[](#step-1-install-the-package-via-composer)

#### Option A: From Packagist (Production)

[](#option-a-from-packagist-production)

```
composer require seangly/laravel-csrm
```

#### Option B: From Local Path (Local Development)

[](#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": "dev-master"
    }
}
```

2. 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

[](#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
-----

[](#usage)

### Initial Setup

[](#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

[](#options)

```
php artisan csrm:install --force
```

The `--force` flag overwrites existing files without prompting.

### Generate New Modules

[](#generate-new-modules)

After initial setup, create new CSRM modules:

```
php artisan csrm:make {name}
```

#### Example

[](#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

[](#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

[](#selective-generation)

Generate only specific components:

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

#### Available Options

[](#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

[](#current-generator-status)

Currently implemented:

- `model`
- `migration`
- `repository`
- `service`
- `controller`

### Overwrite Existing Files

[](#overwrite-existing-files)

```
php artisan csrm:make Order --force
```

Directory Structure
-------------------

[](#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
--------------------------

[](#design-pattern-explanation)

### Repository Layer (Data Access)

[](#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 &amp; Actions)

[](#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

[](#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
-------------

[](#configuration)

### Publishing Assets

[](#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

[](#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
----------

[](#next-steps)

### 1. Run Database Migrations

[](#1-run-database-migrations)

After installation or creating new modules:

```
php artisan migrate
```

### 2. Add Routes Manually

[](#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

[](#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
----------------

[](#common-workflows)

### Create a Complete Module

[](#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

[](#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', '
