PHPackages                             cuongnx/laravel-repo-service-generator - 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. cuongnx/laravel-repo-service-generator

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

cuongnx/laravel-repo-service-generator
======================================

Generate repository-service structure for Laravel with interface and binding

v2.0.8(2mo ago)169MITPHPPHP &gt;=8.1

Since Jul 29Pushed 2mo agoCompare

[ Source](https://github.com/xuancuong220691/laravel-repo-service-generator)[ Packagist](https://packagist.org/packages/cuongnx/laravel-repo-service-generator)[ RSS](/packages/cuongnx-laravel-repo-service-generator/feed)WikiDiscussions main Synced 1mo ago

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

🧱 Laravel Repo-Service Struct Generator
=======================================

[](#-laravel-repo-service-struct-generator)

✅ Generate clean Repository-Service structure with interfaces, bindings, and optional MongoDB support for Laravel 11 and 12+

---

This library provides a powerful artisan command set to generate and manage Repository-Service architecture with optional binding, base classes, and multi-model support. It helps you follow a clean, testable architecture in Laravel projects.

---

🧾 Version Information
---------------------

[](#-version-information)

**Library Version**v1.0.0**Laravel**^11.0, ^12.0**PHP Version**&gt;= 8.1**MongoDB Support**Optional (`--type=m`) via [`mongodb/laravel-mongodb`](https://github.com/mongodb/laravel-mongodb)---

📚 Table of Contents
-------------------

[](#-table-of-contents)

- [Features](#features)
- [Installation](#installation)
- [Full Structure Generation](#create-full-structure-model--repo--service)
- [Create Simple Service](#create-simple-service-interface)
- [Bindings](#bindings)
- [Unbind](#unbind-bindings)
- [Remove Structures](#remove-structures)
- [BaseRepository Methods](#baserepository-methods)
- [BaseService Methods](#baseservice-methods)
- [Advanced Query Conditions](#advanced-query-conditions)
- [Folder Structure](#folder-structure)

---

⚙️ ✅ Features
-------------

[](#️--features)

- Generate Repository, Service, Interface automatically.
- Optional Model generation (Eloquent or MongoDB).
- Auto-bind/unbind to `AppServiceProvider`.
- Middleware-safe service usage.
- Reversible file generation (remove struct).
- Extendable base classes.
- Fast CLI operations.

---

⚙️ Installation
---------------

[](#️-installation)

```
composer require cuongnx/laravel-repo-service-generator
```

> 📦 For MongoDB support:

```
composer require mongodb/laravel-mongodb
```

---

🧱 Create Full Structure (Model + Repo + Service)
------------------------------------------------

[](#-create-full-structure-model--repo--service)

```
php artisan cuongnx:make-struct Post
```

### Options:

[](#options)

FlagDescription`--model`, `--m`Also generate the model class`--type=`Model type: `d` = Eloquent (default), `m` = MongoDB`--no-bind`Skip automatic binding in `AppServiceProvider``--f`, `--force`Overwrite existing files📌 Example with MongoDB:

```
php artisan cuongnx:make-struct Product --m --type=m
```

This command will generate the following files and structure:

```
app/
├── Models/
│   └── Post.php
├── Repositories/
│   ├── Contracts/
│   │   └── PostRepositoryInterface.php
│   └── PostRepository.php
└── Services/
    ├── Contracts/
    │   └── PostServiceInterface.php
    └── PostService.php

```

### File Descriptions:

[](#file-descriptions)

- `app/Models/Post.php`
    → The Eloquent or MongoDB model class for `Post`.
- `app/Repositories/Contracts/PostRepositoryInterface.php`
    → Interface defining methods specific to the `Post` repository.
- `app/Repositories/PostRepository.php`
    → Repository class implementing data access logic for `Post`.
    Extends `BaseRepository` and implements `PostRepositoryInterface`.
- `app/Services/Contracts/PostServiceInterface.php`
    → Interface defining service-level business methods for `Post`.
- `app/Services/PostService.php`
    → Service class implementing business logic related to `Post`.
    Extends `BaseService` and implements `PostServiceInterface`.

📌 If `--no-bind` is not provided, the following bindings will be added to `AppServiceProvider`:

```
$this->app->bind(
    \App\Repositories\Contracts\PostRepositoryInterface::class,
    \App\Repositories\PostRepository::class
);

$this->app->bind(
    \App\Services\Contracts\PostServiceInterface::class,
    \App\Services\PostService::class
);
```

---

🧱 Create Simple Service &amp; Interface (Without implement BaseService)
-----------------------------------------------------------------------

[](#-create-simple-service--interface-without-implement-baseservice)

```
php artisan cuongnx:make-service Custom
```

### Options:

[](#options-1)

FlagDescription`--no-bind`Skip automatic binding in `AppServiceProvider``--f`, `--force`Overwrite existing filesThis command will generate the following files and structure:

```
app/
└── Services/
    ├── Contracts/
    │   └── CustomServiceInterface.php
    └── CustomService.php

```

### File Descriptions:

[](#file-descriptions-1)

- `app/Services/Contracts/CustomServiceInterface.php`
    → Defines custom methods for your `Custom` service logic.
- `app/Services/CustomService.php`
    → Contains business logic related to `Custom`, implements `CustomServiceInterface`.

---

🔌 Bindings
----------

[](#-bindings)

Bind both repository &amp; service: ```
php artisan cuongnx:bind-model User
```

### Options:

[](#options-2)

FlagDescription`--only=repo`Bind only repository`--only=service`Bind only serviceBind individually:

```
php artisan cuongnx:bind-repo User
php artisan cuongnx:bind-service User
```

---

❌ Unbind Bindings
-----------------

[](#-unbind-bindings)

```bash php artisan cuongnx:unbind-model User ``` ### Options:

[](#options-3)

FlagDescription`--only=repo`Unbind only repository`--only=service`Unbind only serviceOr directly:

```
php artisan cuongnx:unbind-repo User
```

```
php artisan cuongnx:unbind-service User
```

---

🧹 Remove Structures
-------------------

[](#-remove-structures)

Remove all (repo + service + optional model): ```
php artisan cuongnx:remove-struct Post --model
```

### Options:

[](#options-4)

FlagDescription`--model`, `-m`Also remove model`--no-unbind`Do not unbind from AppServiceProviderRemove only service:

```
php artisan cuongnx:remove-service Post
```

---

🗄️ BaseRepository Methods
-------------------------

[](#️-baserepository-methods)

All repositories extend `BaseRepository` and automatically gain access to these common data methods.

### 🔍 Read Methods

[](#-read-methods)

MethodDescription`getAll(array $relations = [], array|string|null $orderBy = null)`Get all records with optional relationships and ordering`get(?array $fields = null, array $relations = [], array|string|null $orderBy = null)`Get all records with selected fields, relationships, and ordering`find($id, ?array $fields = null, array $relations = [])`Find by ID with optional field selection and relationships`findBy(string $key, $value, ?array $fields = null, array $relations = [], array|string|null $orderBy = null)`Find a single record by key-value`findByAttributes(array $conditions, ?array $fields = null, array $relations = [], array|string|null $orderBy = null)`Find a single record by multiple attributes`getBy(string $key, $value, ?array $fields = null, array $relations = [], array|string|null $orderBy = null)`Get multiple records by key-value`getByAttributes(array $conditions, ?array $fields = null, array $relations = [], array|string|null $orderBy = null)`Get multiple records by attributes`withTrashed(array $conditions = [], ?array $fields = null, array $relations = [])`Get including soft-deleted records`onlyTrashed(array $conditions = [], ?array $fields = null, array $relations = [])`Get only soft-deleted records### 📊 Pagination

[](#-pagination)

MethodDescription`paginate(int $perPage = 15, array $conditions = [], ?array $fields = null, array $relations = [])`Laravel paginated list with filters and relationships`paginateCustom(array $conditions = [], ?array $fields = null, array $relations = [], array|string|null $orderBy = null, int $page = 1, int $limit = 10)`Custom pagination returning array with data, current\_page, per\_page, total, last\_page### 📈 Aggregate Methods

[](#-aggregate-methods)

MethodDescription`countBy(array $conditions = []): int`Count records by conditions`sum(string $column, array $conditions = []): float|int`Sum a column value with optional conditions`avg(string $column, array $conditions = []): ?float`Average of a column value`max(string $column, array $conditions = []): float|int|null`Maximum value of a column`min(string $column, array $conditions = []): float|int|null`Minimum value of a column### 🔧 Utility Methods

[](#-utility-methods)

MethodDescription`pluck(string $column, ?string $key = null, array $conditions = [])`Pluck values from a column`chunk(int $count, callable $callback, array $conditions = []): bool`Process records in chunks`increment(string $column, int $amount = 1, array $conditions = [], array $extra = []): int`Increment column value`decrement(string $column, int $amount = 1, array $conditions = [], array $extra = []): int`Decrement column value### ✅ Existence Checks

[](#-existence-checks)

MethodDescription`existsBy(string $field, $value): bool`Check if a value exists for a field`existsByAttributes(array $conditions): bool`Check existence by multiple attributes### 📝 Create/Update Methods

[](#-createupdate-methods)

MethodDescription`create(array $data)`Create a new record`update($id, array $data)`Update by ID`updateFields($model, array $fields, array $except = [])`Update specific fields on a model instance`firstOrCreate(array $attributes, array $values = [], array $relations = [])`Find or create a record, returns `[Model, bool $wasCreated]``firstOrNew(array $attributes, array $values = [], array $relations = [])`Find or instantiate (without saving), returns `[Model, bool $isNew]``createOrUpdate(array $attributes, array $values = [], ?array $checkFields = null)`Create or update with field tracking, returns `[Model, bool $wasCreated, bool $wasUpdated, array $changedFields]``updateOrCreate(array $attributes, array $values = [], array $relations = [])`Find and update or create, returns `[Model, bool $wasCreated]`### ❌ Delete / Restore Methods

[](#-delete--restore-methods)

MethodDescription`delete($id)`Soft delete by ID`deleteBy(array $conditions): int`Delete by conditions, returns number of deleted records`restore($id): bool`Restore soft-deleted record`forceDelete($id): bool`Permanently delete record---

🧠 BaseService Methods
---------------------

[](#-baseservice-methods)

All services extend `BaseService` and delegate to the repository methods. The service layer is where you implement business logic on top of the repository.

Services have access to all BaseRepository methods through their repository instance. You can add custom business logic methods in your service classes.

---

🔍 Advanced Query Conditions
---------------------------

[](#-advanced-query-conditions)

The `BaseRepository` supports flexible query conditions for both Eloquent and MongoDB.

### 1️⃣ Simple Conditions

[](#1️⃣-simple-conditions)

```
$conditions = [
    'status' => 'active',
    'user_id' => 123
];

$posts = $postRepo->getByAttributes($conditions);
```

### 2️⃣ Comparison Operators

[](#2️⃣-comparison-operators)

```
$conditions = [
    'price' => ['>=', 100],
    'stock' => ['', 4.5]
];

$products = $productRepo->getByAttributes($conditions);
```

### 3️⃣ MongoDB Operators

[](#3️⃣-mongodb-operators)

```
// Using MongoDB $gte, $lte operators
$conditions = [
    'expired_at' => [
        '$gte' => now(),
        '$lte' => now()->addDays(30)
    ]
];

// Using MongoDB $elemMatch for array fields
$conditions = [
    'tags' => [
        '$elemMatch' => ['name' => 'Laravel', 'type' => 'framework']
    ]
];
```

### 4️⃣ Date Range Queries

[](#4️⃣-date-range-queries)

```
// Using from/to syntax
$conditions = [
    'created_at' => [
        'from' => now()->subDays(7),
        'to' => now()
    ]
];

// Using min/max syntax
$conditions = [
    'price' => [
        'min' => 100,
        'max' => 1000
    ]
];

// Using between operator
$conditions = [
    'age' => ['between', [18, 65]]
];
```

### 5️⃣ IN / NOT IN Queries

[](#5️⃣-in--not-in-queries)

```
$conditions = [
    'status' => ['in', ['active', 'pending', 'processing']],
    'category_id' => ['not_in', [5, 10, 15]]
];
```

### 6️⃣ NULL Checks

[](#6️⃣-null-checks)

```
$conditions = [
    'deleted_at' => ['null'],
    'email_verified_at' => ['not_null']
];
```

### 7️⃣ Combined Complex Queries

[](#7️⃣-combined-complex-queries)

```
$conditions = [
    'status' => 'active',
    'price' => [
        '$gte' => 100,
        '$lte' => 1000
    ],
    'category_id' => ['in', [1, 2, 3]],
    'created_at' => [
        'from' => now()->subMonth(),
        'to' => now()
    ],
    'tags' => [
        '$elemMatch' => ['featured' => true]
    ]
];

$products = $productRepo->getByAttributes(
    conditions: $conditions,
    fields: ['id', 'name', 'price'],
    relations: ['category', 'images'],
    orderBy: ['created_at' => 'desc']
);
```

### 8️⃣ Ordering Results

[](#8️⃣-ordering-results)

```
// Simple ordering (string)
$orderBy = 'created_at'; // defaults to 'asc'

// Single field ordering (array)
$orderBy = ['created_at' => 'desc'];

// Multiple field ordering
$orderBy = [
    'status' => 'asc',
    'created_at' => 'desc'
];

// Alternative syntax with indexed arrays
$orderBy = [
    ['status', 'asc'],
    ['created_at', 'desc']
];
```

### Real-World Examples

[](#real-world-examples)

#### Get Active Products Expiring Soon

[](#get-active-products-expiring-soon)

```
$products = $productRepo->getByAttributes([
    'status' => 'active',
    'expired_at' => [
        '$gte' => now(),
        '$lte' => now()->addDays(30)
    ]
], orderBy: ['expired_at' => 'asc']);
```

#### Get Orders from Last Month in Price Range

[](#get-orders-from-last-month-in-price-range)

```
$orders = $orderRepo->getByAttributes([
    'total_amount' => [
        'min' => 1000,
        'max' => 5000
    ],
    'created_at' => [
        'from' => now()->subMonth()->startOfMonth(),
        'to' => now()->subMonth()->endOfMonth()
    ],
    'status' => ['in', ['completed', 'shipped']]
], relations: ['user', 'items']);
```

#### MongoDB Array Query with Tags

[](#mongodb-array-query-with-tags)

```
$posts = $postRepo->getByAttributes([
    'published' => true,
    'tags' => [
        '$elemMatch' => [
            'name' => 'Laravel',
            'type' => 'framework'
        ]
    ],
    'views' => ['>=', 1000]
], orderBy: ['views' => 'desc']);
```

📁 Folder Structure
------------------

[](#-folder-structure)

```
app/
├── Repositories/
│   ├── Contracts/
│   │   ├── BaseRepositoryInterface.php
│   │   ├── UserRepositoryInterface.php
│   │   └── PostRepositoryInterface.php
│   ├── BaseRepository.php
│   ├── UserRepository.php
│   └── PostRepository.php
├── Services/
│   ├── Contracts/
│   │   ├── BaseServiceInterface.php
│   │   ├── CustomServiceInterface.php
│   │   ├── UserServiceInterface.php
│   │   └── PostServiceInterface.php
│   ├── BaseService.php
│   ├── CustomService.php
│   ├── UserService.php
│   └── PostService.php
└── Models/
    ├── User.php
    └── Post.php

```

📬 Contact
---------

[](#-contact)

- Email:

---

📝 License
---------

[](#-license)

- MIT License © [Cuong Nguyen](mailto:xuancuong220691@gmail.com)

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance86

Actively maintained with recent releases

Popularity12

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~22 days

Total

11

Last Release

67d ago

Major Versions

v1.0.1 → v2.0.02025-12-04

### Community

Maintainers

![](https://www.gravatar.com/avatar/951e95d597ea9f09e996482a483501ca3eba1233872148e8513405e9c87fe23b?d=identicon)[xuancuong220691](/maintainers/xuancuong220691)

---

Top Contributors

[![xuancuong220691](https://avatars.githubusercontent.com/u/12405391?v=4)](https://github.com/xuancuong220691 "xuancuong220691 (13 commits)")

### Embed Badge

![Health badge](/badges/cuongnx-laravel-repo-service-generator/health.svg)

```
[![Health](https://phpackages.com/badges/cuongnx-laravel-repo-service-generator/health.svg)](https://phpackages.com/packages/cuongnx-laravel-repo-service-generator)
```

###  Alternatives

[barryvdh/laravel-ide-helper

Laravel IDE Helper, generates correct PHPDocs for all Facade classes, to improve auto-completion.

14.9k123.0M687](/packages/barryvdh-laravel-ide-helper)[orchestra/canvas

Code Generators for Laravel Applications and Packages

21017.2M158](/packages/orchestra-canvas)[illuminate/pipeline

The Illuminate Pipeline package.

9446.6M213](/packages/illuminate-pipeline)[illuminate/pagination

The Illuminate Pagination package.

10532.5M862](/packages/illuminate-pagination)[spatie/laravel-pjax

A pjax middleware for Laravel 5

513371.8k11](/packages/spatie-laravel-pjax)[spatie/laravel-mix-preload

Add preload and prefetch links based your Mix manifest

169176.0k2](/packages/spatie-laravel-mix-preload)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
