PHPackages                             nameless/laravel-api-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. [API Development](/categories/api)
4. /
5. nameless/laravel-api-generator

ActiveLibrary[API Development](/categories/api)

nameless/laravel-api-generator
==============================

A professional Laravel API generator that automatically creates complete API structures with clean architecture, type safety, and best practices

v3.3.1(1mo ago)1920MITPHPPHP ^8.1CI passing

Since Jan 28Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/Nameless0l/laravel-api-generator)[ Packagist](https://packagist.org/packages/nameless/laravel-api-generator)[ RSS](/packages/nameless-laravel-api-generator/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (14)Versions (21)Used By (0)

Laravel API Generator
=====================

[](#laravel-api-generator)

[![Latest Version on Packagist](https://camo.githubusercontent.com/059733bb467a2368d834dd6324ea4bfdb82d258d0eec23ff274f3b7e7d1b5618/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6e616d656c6573732f6c61726176656c2d6170692d67656e657261746f722e737667)](https://packagist.org/packages/nameless/laravel-api-generator)[![Total Downloads](https://camo.githubusercontent.com/88c1299de954a24b7f146bf2be70cec7d0396e21e9f46e7fbc2e870063802186/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6e616d656c6573732f6c61726176656c2d6170692d67656e657261746f722e737667)](https://packagist.org/packages/nameless/laravel-api-generator)[![License](https://camo.githubusercontent.com/1f8825c6c66780421287eb862fbccc4f142027643ec23b75dbbd9f7a2c8706fe/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6e616d656c6573732f6c61726176656c2d6170692d67656e657261746f722e737667)](https://packagist.org/packages/nameless/laravel-api-generator)

A professional Laravel package that generates complete, production-ready REST API structures from a single command. Built with clean architecture principles, PHP 8.1+ features, and Laravel best practices.

[![Demo](docs/demo.gif)](docs/demo.gif)

### VS Code Extension

[](#vs-code-extension)

A visual interface is available: [laravel-api-generator-vscode](https://github.com/Nameless0l/laravel-api-generator-vscode). Generate APIs, run migrations, tests, and browse documentation -- all from VS Code without touching the terminal.

### v3.3 -- Generate, seed, test, and document in seconds

[](#v33----generate-seed-test-and-document-in-seconds)

**Swagger UI** -- automatic interactive API documentation with Scramble:

[![Scramble Endpoints](docs/scramble-docs.png)](docs/scramble-docs.png)

**Validation schemas** -- your FormRequest rules become typed, documented constraints:

[![Scramble Schemas](docs/scramble-schemas.png)](docs/scramble-schemas.png)

**Database seeding** -- 10 records per entity, ready to use:

[![Seeded Database](docs/seeded-database.png)](docs/seeded-database.png)

---

Architecture
------------

[](#architecture)

[![Architecture Diagram](docs/architecture-diagram.png)](docs/architecture-diagram.png)

---

What it generates
-----------------

[](#what-it-generates)

From a single command, the package creates **12 files** per entity and registers the API route:

LayerFileLocationModel`Post.php``app/Models/`Controller`PostController.php``app/Http/Controllers/`Service`PostService.php``app/Services/`DTO`PostDTO.php``app/DTO/`Request`PostRequest.php``app/Http/Requests/`Resource`PostResource.php``app/Http/Resources/`Policy`PostPolicy.php``app/Policies/`Factory`PostFactory.php``database/factories/`Seeder`PostSeeder.php``database/seeders/`Migration`*_create_posts_table.php``database/migrations/`Feature Test`PostControllerTest.php``tests/Feature/`Unit Test`PostServiceTest.php``tests/Unit/`Route`apiResource` entry`routes/api.php`---

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

[](#installation)

```
composer require nameless/laravel-api-generator
```

The service provider is auto-discovered. No additional configuration required.

---

Quick start
-----------

[](#quick-start)

### Single entity

[](#single-entity)

```
php artisan make:fullapi Post --fields="title:string,content:text,published:boolean"
```

### With soft deletes

[](#with-soft-deletes)

```
php artisan make:fullapi Post --fields="title:string,content:text" --soft-deletes
```

This adds the `SoftDeletes` trait to the model, a `softDeletes()` column in the migration, and `restore` / `forceDelete` endpoints with their routes.

### With Postman collection export

[](#with-postman-collection-export)

```
php artisan make:fullapi Post --fields="title:string,content:text" --postman
```

Generates a `postman_collection.json` at the project root, ready to import. Each entity gets a folder with List, Create, Show, Update, and Delete requests pre-configured with sample data.

### With Sanctum authentication

[](#with-sanctum-authentication)

```
php artisan make:fullapi Post --fields="title:string,content:text" --auth
```

This scaffolds a complete Sanctum-based auth system: `AuthController` (register, login, logout, user), `LoginRequest`, `RegisterRequest`, auth routes, and wraps your API resource routes inside `auth:sanctum` middleware.

### Interactive wizard

[](#interactive-wizard)

```
php artisan make:fullapi --interactive
```

A step-by-step guided setup that lets you define the entity name, add fields one by one (with type, nullable, unique, and default value options), configure relationships, and preview everything before generation.

### All options combined

[](#all-options-combined)

```
php artisan make:fullapi Post --fields="title:string,content:text" --soft-deletes --postman --auth
```

### Bulk generation from JSON

[](#bulk-generation-from-json)

Create a `class_data.json` file at your project root (or [download the sample Blog schema](examples/class_data.json) with Author, Category, Article, and Tag entities):

```
[
  {
    "name": "User",
    "attributes": [
      {"name": "name", "_type": "string"},
      {"name": "email", "_type": "string"}
    ],
    "oneToManyRelationships": [
      {"role": "posts", "comodel": "Post"}
    ]
  },
  {
    "name": "Post",
    "attributes": [
      {"name": "title", "_type": "string"},
      {"name": "content", "_type": "text"}
    ],
    "manyToOneRelationships": [
      {"role": "user", "comodel": "User"}
    ]
  }
]
```

Then run:

```
php artisan make:fullapi
```

### Delete generated API

[](#delete-generated-api)

```
# Delete a specific entity
php artisan delete:fullapi Post

# Delete all entities defined in class_data.json
php artisan delete:fullapi
```

---

Command reference
-----------------

[](#command-reference)

```
php artisan make:fullapi {name?} {--fields=} {--soft-deletes} {--postman} {--auth} {--interactive}

```

Argument / OptionDescription`name`Entity name (PascalCase). Omit to use JSON mode.`--fields`Field definitions in `name:type` format, comma-separated.`--soft-deletes`Add SoftDeletes trait, migration column, restore/forceDelete endpoints.`--postman`Export a Postman v2.1 collection after generation.`--auth`Scaffold Sanctum authentication (AuthController, requests, routes, middleware).`--interactive`Launch the step-by-step wizard for guided entity creation.---

Supported field types
---------------------

[](#supported-field-types)

TypeDatabase columnPHP typeValidation rule`string``VARCHAR(255)``string``string|max:255``text``TEXT``string``string``integer` / `int``INTEGER``int``integer``bigint``BIGINTEGER``int``integer``boolean` / `bool``BOOLEAN``bool``boolean``float` / `decimal``DECIMAL(8,2)``float``numeric``json``JSON``array``json``date` / `datetime` / `timestamp``TIMESTAMP``DateTimeInterface``date``uuid``UUID``string``uuid`---

Relationship types
------------------

[](#relationship-types)

Supported in JSON mode via `class_data.json`:

JSON keyEloquent methodForeign key`oneToOneRelationships``hasOne()`On related table`oneToManyRelationships``hasMany()`On related table`manyToOneRelationships``belongsTo()`On current table`manyToManyRelationships``belongsToMany()`Pivot tableModel inheritance is also supported via the `"parent"` key in JSON definitions.

---

Generated code examples
-----------------------

[](#generated-code-examples)

### Controller

[](#controller)

The generated controller uses constructor injection, DTOs, and delegates to the service layer. The `index` endpoint supports query parameter filtering out of the box.

```
class PostController extends Controller
{
    public function __construct(
        private readonly PostService $service
    ) {}

    public function index(Request $request)
    {
        $posts = $this->service->getAll($request->query());
        return PostResource::collection($posts);
    }

    public function store(PostRequest $request)
    {
        $dto = PostDTO::fromRequest($request);
        $post = $this->service->create($dto);
        return new PostResource($post);
    }

    public function show(Post $post)
    {
        return new PostResource($post);
    }

    public function update(PostRequest $request, Post $post)
    {
        $dto = PostDTO::fromRequest($request);
        $updatedPost = $this->service->update($post, $dto);
        return new PostResource($updatedPost);
    }

    public function destroy(Post $post)
    {
        $this->service->delete($post);
        return response(null, 204);
    }
}
```

### Service

[](#service)

The service layer handles business logic and supports filtering on fillable fields. Route parameters are accepted as `int|string` to work seamlessly with `declare(strict_types=1)`. With `--soft-deletes`, it also includes `restore()` and `forceDelete()` methods.

```
class PostService
{
    public function getAll(array $filters = []): Collection
    {
        $query = Post::query();

        foreach ($filters as $field => $value) {
            if (in_array($field, (new Post())->getFillable(), true)) {
                $query->where($field, $value);
            }
        }

        return $query->get();
    }

    public function find(int|string $id): Post
    {
        return Post::findOrFail($id);
    }

    public function create(PostDTO $dto): Post
    {
        return Post::create(get_object_vars($dto));
    }

    public function update(Post $post, PostDTO $dto): Post
    {
        $post->update(get_object_vars($dto));
        return $post->fresh();
    }

    public function delete(Post $post): bool
    {
        return $post->delete();
    }
}
```

### DTO

[](#dto)

Readonly data transfer objects with typed properties and a factory method:

```
readonly class PostDTO
{
    public function __construct(
        public ?string $title,
        public ?string $content,
        public ?bool $published
    ) {}

    public static function fromRequest(PostRequest $request): self
    {
        return new self(
            $request->input('title'),
            $request->input('content'),
            (bool) $request->input('published')
        );
    }
}
```

### Feature test

[](#feature-test)

Automatically generated PHPUnit tests covering all CRUD endpoints:

```
class PostControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_can_list_posts(): void
    {
        Post::factory()->count(3)->create();
        $response = $this->getJson('/api/posts');
        $response->assertStatus(200)->assertJsonCount(3, 'data');
    }

    public function test_can_create_post(): void
    {
        $data = ['title' => 'test_title', 'content' => 'Test text content'];
        $response = $this->postJson('/api/posts', $data);
        $response->assertStatus(201);
        $this->assertDatabaseHas('posts', $data);
    }

    // ... show, update, delete, validation tests
}
```

---

Query parameter filtering
-------------------------

[](#query-parameter-filtering)

All generated `index` endpoints support filtering by any fillable field via query parameters:

```
GET /api/posts?published=true
GET /api/users?name=John
GET /api/products?category=electronics&in_stock=true

```

Only fields declared in the model's `$fillable` array are accepted as filters. Other parameters are silently ignored.

---

Soft deletes
------------

[](#soft-deletes)

When using `--soft-deletes`, the generator adds:

- `SoftDeletes` trait and import to the model
- `$table->softDeletes()` to the migration
- `restore()` and `forceDelete()` methods to the controller and service
- Two additional routes:

```
POST   /api/posts/{id}/restore
DELETE /api/posts/{id}/force-delete

```

---

Postman collection
------------------

[](#postman-collection)

The `--postman` flag generates a `postman_collection.json` file at the project root. The collection follows the Postman v2.1 schema and includes:

- A folder per entity
- Pre-configured requests for List, Create, Show, Update, and Delete
- Sample request bodies with appropriate field values
- A `base_url` variable (defaults to `http://localhost:8000/api`)

Import the file directly into Postman to start testing immediately.

---

Sanctum authentication
----------------------

[](#sanctum-authentication)

The `--auth` flag scaffolds a complete token-based authentication system using Laravel Sanctum:

**Generated files:**

- `app/Http/Controllers/AuthController.php` -- register, login, logout, user endpoints
- `app/Http/Requests/LoginRequest.php` -- email + password validation
- `app/Http/Requests/RegisterRequest.php` -- name, email, password + confirmation validation

**Generated routes:**

```
// Public
POST /api/register
POST /api/login

// Protected (auth:sanctum)
POST /api/logout
GET  /api/user

// Your API resources are also wrapped in auth:sanctum
GET  /api/posts          (requires token)
POST /api/posts          (requires token)
// ...
```

After running with `--auth`, install Sanctum if not already present:

```
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
```

Add the `HasApiTokens` trait to your `User` model, and your API is secured.

---

Interactive mode
----------------

[](#interactive-mode)

The `--interactive` flag launches a step-by-step wizard that guides you through entity creation:

1. **Entity name** -- enter the model name in PascalCase
2. **Fields** -- add fields one by one, choosing type, nullable, unique, and default value for each
3. **Relationships** -- optionally add belongsTo, hasMany, hasOne, or belongsToMany relations
4. **Options** -- enable soft deletes, Sanctum auth, Postman export
5. **Preview** -- review the full entity definition and file list before confirming
6. **Generate** -- confirm and generate all files

This mode is ideal for developers who prefer a guided experience or want to configure field constraints (unique, defaults) that aren't available in the `--fields` string syntax.

---

Extending the generator
-----------------------

[](#extending-the-generator)

Create a custom generator by extending `AbstractGenerator`:

```
use nameless\CodeGenerator\EntitiesGenerator\AbstractGenerator;
use nameless\CodeGenerator\ValueObjects\EntityDefinition;

class CustomGenerator extends AbstractGenerator
{
    public function getType(): string
    {
        return 'Custom';
    }

    public function getOutputPath(EntityDefinition $definition): string
    {
        return app_path("Custom/{$definition->name}Custom.php");
    }

    protected function getStubName(): string
    {
        return 'custom'; // loads stubs/custom.stub
    }

    protected function getReplacements(EntityDefinition $definition): array
    {
        return ['modelName' => $definition->name];
    }

    protected function generateContent(EntityDefinition $definition): string
    {
        return $this->processStub($definition);
    }
}
```

Register it in your service provider and it will be called automatically during generation.

---

API documentation with Scramble
-------------------------------

[](#api-documentation-with-scramble)

The package integrates seamlessly with [Scramble](https://github.com/dedoc/scramble) to provide **automatic, interactive API documentation** -- no annotations or manual setup required.

[![Scramble API Docs](docs/scramble-docs.png)](docs/scramble-docs.png)

### Setup

[](#setup)

```
composer require dedoc/scramble --dev
php artisan serve
```

Then open  in your browser.

### What you get

[](#what-you-get)

Scramble automatically analyzes your generated controllers, requests, and resources to produce a full **OpenAPI 3.x specification** with:

- **Interactive Swagger UI** -- test endpoints directly from the browser with "Send API Request"
- **Auto-detected schemas** -- `ProductRequest`, `ProductResource`, etc. are inferred from your FormRequest rules and API Resource structure
- **Validation rules as constraints** -- `required|string|max:255` becomes a required string field with ` **Note:** Scramble is a dev dependency. It won't affect your production deployment.

---

Database seeding
----------------

[](#database-seeding)

Generated seeders are automatically registered in `DatabaseSeeder.php`. After generating your API and running migrations:

```
php artisan migrate:fresh --seed
```

Each entity seeder creates **10 records** using the generated factory. The `delete:fullapi` command also cleans up the seeder registration.

[![Seeded Database](docs/seeded-database.png)](docs/seeded-database.png)

---

Development
-----------

[](#development)

```
# Install dependencies
composer install

# Run tests
composer test

# Static analysis
composer analyse

# Code formatting
composer format
```

### Local testing in a Laravel project

[](#local-testing-in-a-laravel-project)

Add the package as a path repository in your Laravel project's `composer.json`:

```
{
    "repositories": [
        {
            "type": "path",
            "url": "../laravel-api-generator",
            "options": {"symlink": true}
        }
    ],
    "require": {
        "nameless/laravel-api-generator": "@dev"
    }
}
```

Then run `composer update`.

---

Requirements
------------

[](#requirements)

- PHP &gt;= 8.2
- Laravel 10.x, 11.x, or 12.x

---

Contributing
------------

[](#contributing)

Contributions are welcome. Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.

---

Security
--------

[](#security)

If you discover a security vulnerability, please email  instead of using the issue tracker.

---

Credits
-------

[](#credits)

- [Mbassi Loic Aron](https://github.com/Nameless0l)

---

Changelog
---------

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md) for the full version history.

---

License
-------

[](#license)

MIT. See [LICENSE](LICENSE.md) for details.

###  Health Score

47

—

FairBetter than 93% of packages

Maintenance99

Actively maintained with recent releases

Popularity16

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity55

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 ~27 days

Recently: every ~5 days

Total

17

Last Release

34d ago

Major Versions

2.0.6 → 3.0.02025-06-28

### Community

Maintainers

![](https://www.gravatar.com/avatar/bb61998c811494c4cab8cd18b5572561011643399ddb1ad376234bbc4e5fd7de?d=identicon)[Nameless0l](/maintainers/Nameless0l)

---

Top Contributors

[![Nameless0l](https://avatars.githubusercontent.com/u/108153213?v=4)](https://github.com/Nameless0l "Nameless0l (63 commits)")

---

Tags

newapilaravelgeneratorcode generatorartisancruddtoservice layerclean architecture

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/nameless-laravel-api-generator/health.svg)

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

PHPackages © 2026

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