PHPackages                             born-mt/laravel-crud-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. born-mt/laravel-crud-generator

ActiveLibrary

born-mt/laravel-crud-generator
==============================

A Symfony-style interactive entity generator for Laravel with models, migrations, and relationships

v1.1.3(6mo ago)123MITPHPPHP ^8.1|^8.2|^8.3CI failing

Since Oct 24Pushed 6mo agoCompare

[ Source](https://github.com/Born-MT/laravel-crud-generator)[ Packagist](https://packagist.org/packages/born-mt/laravel-crud-generator)[ RSS](/packages/born-mt-laravel-crud-generator/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (6)Versions (3)Used By (0)

Laravel CRUD Generator
======================

[](#laravel-crud-generator)

[![CircleCI](https://camo.githubusercontent.com/a5ba7663bc356cbf103e71fcb3baf51eadaeee1260c73eb73f2917f83150db5e/68747470733a2f2f636972636c6563692e636f6d2f67682f426f726e2d4d542f6c61726176656c2d637275642d67656e657261746f722f747265652f6d61696e2e7376673f7374796c653d737667)](https://circleci.com/gh/Born-MT/laravel-crud-generator/tree/main)[![Latest Version on Packagist](https://camo.githubusercontent.com/3186b6f15b6c13edf3942dd355b0a82030ea0ebf241802a74cc860390c7438ce/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f626f726e2d6d742f6c61726176656c2d637275642d67656e657261746f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/born-mt/laravel-crud-generator)[![Total Downloads](https://camo.githubusercontent.com/16f6eef57140c2ee9458ddab7a99ee2758e26e7cf13511889f45703bc6d6907f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f626f726e2d6d742f6c61726176656c2d637275642d67656e657261746f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/born-mt/laravel-crud-generator)[![License](https://camo.githubusercontent.com/f47eb95f228028f75a0f3a79943527f221b7d860fff42e4274647aa4cf5538b6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f626f726e2d6d742f6c61726176656c2d637275642d67656e657261746f722e7376673f7374796c653d666c61742d737175617265)](LICENSE)

A Symfony-style interactive entity generator for Laravel that streamlines model and migration creation with an intuitive, step-by-step interface.

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

[](#table-of-contents)

- [Features](#features)
- [Installation](#installation)
- [Usage](#usage)
- [Supported Field Types](#supported-field-types)
- [Configuration](#configuration)
- [Requirements](#requirements)
- [Contributing](#contributing)
- [License](#license)

Features
--------

[](#features)

- Interactive command-line interface inspired by Symfony's `make:entity`
- Generate Eloquent models with properties, relationships, casts, and guarded attributes
- Automatically create database migrations with all columns and indexes
- **Generate CRUD controllers** - Web resource and/or API resource controllers
- Support for various field types (string, integer, boolean, date, json, etc.)
- Built-in relationship handling (belongsTo, hasMany, hasOne, belongsToMany, morphTo, morphMany)
- Update existing models and migrations
- Smart property detection when updating existing entities
- Configurable defaults via config file
- Comprehensive test coverage

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

[](#installation)

Install the package via Composer:

```
composer require born-mt/laravel-crud-generator
```

The package will auto-register via Laravel's package discovery.

### Publish Configuration (Optional)

[](#publish-configuration-optional)

Publish the config file to customize defaults:

```
php artisan vendor:publish --tag=crud-generator-config
```

This will create `config/crud-generator.php` where you can customize:

- Model namespace
- Default string length
- Timestamps behavior
- Soft deletes prompts
- UUID usage

### Updating the Package

[](#updating-the-package)

To update to the latest version:

```
composer update born-mt/laravel-crud-generator
```

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

Create a new entity:

```
php artisan make:entity Product
```

### Interactive Flow Example

[](#interactive-flow-example)

```
$ php artisan make:entity Product

Creating a new entity: Product

New property name (press  to stop adding fields):
> name

Field type (string, text, integer, boolean, date, datetime, json, belongsTo, hasMany, etc.):
> string

Length [255]:
> 255

Can this field be null in the database? (yes/no) [no]:
> no

Should this field be unique? (yes/no) [no]:
> no

New property name (press  to stop adding fields):
> price

Field type:
> decimal

Precision [8]:
> 10

Scale [2]:
> 2

Can this field be null in the database? (yes/no) [no]:
> no

New property name (press  to stop adding fields):
> category

Field type:
> belongsTo

Related model name:
> Category

What should the inverse relationship be called?
> products

On delete action (cascade, set null, restrict) [restrict]:
> cascade

New property name (press  to stop adding fields):
>

✓ Model created: app/Models/Product.php
✓ Migration created: database/migrations/2024_10_23_120000_create_products_table.php

Success! Next steps:
- Review your model and migration
- Run: php artisan migrate
```

### Updating Existing Entities

[](#updating-existing-entities)

Update an existing model with new fields:

```
php artisan make:entity Product --update
```

When updating an existing entity:

1. The command loads existing properties from the model
2. You can add new properties interactively
3. The model file is updated with new casts and relationships
4. A new migration file is created to add the new columns
5. The migration's `down()` method will properly drop the new columns if rolled back

Example update flow:

```
$ php artisan make:entity Product --update

Creating a new entity: Product

Loading existing model properties...
Found 3 existing properties in the model.

New property name (press  to stop adding fields):
> stock_quantity

Field type:
> integer

Should this field be unsigned? (yes/no) [yes]:
> yes

Can this field be null in the database? (yes/no) [no]:
> no

New property name (press  to stop adding fields):
>

Adding 1 new properties to the model.
✓ Model updated: app/Models/Product.php
✓ Migration created: database/migrations/2024_10_23_123456_add_fields_to_products_table.php

Success! Next steps:
- Review your model and migration
- Run: php artisan migrate (to add the new columns)
```

### Force Overwrite

[](#force-overwrite)

Overwrite existing files:

```
php artisan make:entity Product --force
```

### Generating Controllers

[](#generating-controllers)

The package can automatically generate controllers after creating your entity:

#### Interactive Prompt (Recommended)

[](#interactive-prompt-recommended)

When creating an entity, you'll be prompted:

```
$ php artisan make:entity Product

# ... (field creation process) ...

Do you want to generate controllers? (yes/no) [no]:
> yes

Controller Options:
Generate web resource controller? (yes/no) [yes]:
> yes

Generate API resource controller? (yes/no) [no]:
> yes

✓ Model created: app/Models/Product.php
✓ Migration created: database/migrations/2024_10_23_120000_create_products_table.php
✓ Web controller created: app/Http/Controllers/ProductController.php
✓ API controller created: app/Http/Controllers/Api/ProductController.php

Success! Next steps:
- Review your model and migration
- Run: php artisan migrate
- Review your generated controllers
- Add routes for web controller in routes/web.php
- Add routes for API controller in routes/api.php
```

#### Using Flags

[](#using-flags)

Generate specific controller types using command flags:

```
# Generate web resource controller only
php artisan make:entity Product --web

# Generate API resource controller only
php artisan make:entity Product --api

# Generate both
php artisan make:entity Product --web --api

# Prompt for controller options
php artisan make:entity Product --controller
```

#### What Gets Generated

[](#what-gets-generated)

**Web Resource Controller** (`app/Http/Controllers/ProductController.php`):

Full CRUD implementation with:

- `index()` - Display paginated listing with views
- `create()` - Show creation form
- `store()` - Validate and create new record, redirect with success message
- `show()` - Display single resource
- `edit()` - Show edit form
- `update()` - Validate and update record, redirect with success message
- `destroy()` - Delete record, redirect with success message

Generated controller includes:

```
public function index(): View
{
    $products = Product::latest()->paginate(15);
    return view('products.index', compact('products'));
}

public function store(Request $request): RedirectResponse
{
    $validated = $request->validate([
        // Add your validation rules here
    ]);

    $product = Product::create($validated);

    return redirect()
        ->route('products.show', $product)
        ->with('success', 'Product created successfully.');
}
// ... and more
```

**API Resource Controller** (`app/Http/Controllers/Api/ProductController.php`):

RESTful JSON API with:

- `index()` - Return paginated JSON listing
- `store()` - Validate, create, and return JSON response with 201 status
- `show()` - Return single resource as JSON
- `update()` - Validate, update, and return JSON response
- `destroy()` - Delete and return success JSON

Generated controller includes:

```
public function index(): JsonResponse
{
    $products = Product::latest()->paginate(15);
    return response()->json($products);
}

public function store(Request $request): JsonResponse
{
    $validated = $request->validate([
        // Add your validation rules here
    ]);

    $product = Product::create($validated);

    return response()->json([
        'message' => 'Product created successfully.',
        'data' => $product,
    ], 201);
}
// ... and more
```

**Key Features:**

- ✅ Full CRUD operations pre-implemented
- ✅ Proper HTTP status codes (API)
- ✅ Validation placeholders ready to customize
- ✅ Success messages and redirects (Web)
- ✅ Route model binding
- ✅ Pagination support
- ✅ Latest records first (descending order)
- ✅ Type-hinted return types
- ✅ PSR-12 compliant code

How Updates Work
----------------

[](#how-updates-work)

When you run `php artisan make:entity YourModel --update`, the package:

1. **Parses the existing model** - Extracts existing properties from the `$casts` array and relationship methods
2. **Shows existing properties** - Displays a count of properties already in the model
3. **Collects new properties** - Allows you to add new fields interactively (skips properties that already exist)
4. **Updates the model file** - Merges new properties into:
    - `$casts` array (adds new type casts)
    - Import statements (adds new relationship imports if needed)
    - Relationship methods (appends new methods to the end of the class)
5. **Generates an update migration** - Creates a new migration with:
    - `up()` method: Uses `Schema::table()` to add only new columns
    - `down()` method: Uses `dropColumn()` to remove the new columns if rolled back

The original model structure is preserved - only new casts and relationships are appended.

Supported Field Types
---------------------

[](#supported-field-types)

### Basic Types

[](#basic-types)

- `string` - VARCHAR (configurable length, default 255)
- `text` - TEXT
- `integer` - INTEGER
- `bigInteger` - BIGINT
- `boolean` - BOOLEAN
- `decimal` - DECIMAL (configurable precision and scale)
- `float` - FLOAT
- `date` - DATE
- `datetime` - DATETIME
- `timestamp` - TIMESTAMP
- `json` - JSON
- `uuid` - UUID

### Relationship Types

[](#relationship-types)

- `belongsTo` - Many-to-One (creates foreign key in migration)
- `hasMany` - One-to-Many (no migration changes)
- `hasOne` - One-to-One (no migration changes)
- `belongsToMany` - Many-to-Many (prompts for pivot table info)
- `morphTo` - Polymorphic relation
- `morphMany` - Polymorphic one-to-many

Field Options
-------------

[](#field-options)

For each property, you can specify:

- **Length** (string types): Custom length, default 255
- **Nullable**: Whether the field can be null
- **Unique**: Whether to add a unique constraint
- **Default value**: Optional default value
- **Unsigned**: For integer types
- **Index**: Whether to add an index
- **Precision/Scale**: For decimal types

For relationships:

- **Related model name**
- **Foreign key name** (with smart defaults)
- **Inverse relationship method name**
- **On delete action** (cascade, set null, restrict)

Configuration
-------------

[](#configuration)

The package comes with a configuration file that can be published:

```
php artisan vendor:publish --tag=crud-generator-config
```

Configuration options (`config/crud-generator.php`):

```
return [
    // Default namespace for generated models
    'model_namespace' => 'App\\Models',

    // Default length for string fields
    'default_string_length' => 255,

    // Auto-add timestamps
    'timestamps' => true,

    // Prompt for soft deletes
    'soft_deletes' => false,

    // Use UUIDs instead of auto-increment IDs
    'use_uuids' => false,
];
```

Generated Files
---------------

[](#generated-files)

### Model File

[](#model-file)

The command generates a complete Eloquent model with:

- Proper namespace and imports
- `$guarded` array protecting only the primary key (prevents model bloat)
- `$casts` array with appropriate type casts
- Relationship methods
- Clean, PSR-12 compliant code

Example:

```
