PHPackages                             wink/wink-model-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. [Database &amp; ORM](/categories/database)
4. /
5. wink/wink-model-generator

ActiveLibrary[Database &amp; ORM](/categories/database)

wink/wink-model-generator
=========================

A powerful Laravel package that automatically generates Eloquent models from your existing database schema, supporting both MySQL and SQLite databases

v0.4.0(10mo ago)022[3 PRs](https://github.com/wink-/wink-model-generator/pulls)MITPHPPHP ^8.3CI failing

Since Jan 17Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/wink-/wink-model-generator)[ Packagist](https://packagist.org/packages/wink/wink-model-generator)[ GitHub Sponsors](https://github.com/sponsors/wink-)[ RSS](/packages/wink-wink-model-generator/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (7)Dependencies (11)Versions (29)Used By (0)

Laravel Model Generator
=======================

[](#laravel-model-generator)

[![Latest Version on Packagist](https://camo.githubusercontent.com/3dea6d4a183b6668b1d6a5b5e589f4b5c2ae8c3efb5cf7cab5495dbd5a866701/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f77696e6b2f77696e6b2d6d6f64656c2d67656e657261746f722e737667)](https://packagist.org/packages/wink/wink-model-generator)[![Tests](https://github.com/wink-/wink-model-generator/actions/workflows/tests.yml/badge.svg?branch=main)](https://github.com/wink-/wink-model-generator/actions/workflows/tests.yml)[![Total Downloads](https://camo.githubusercontent.com/b6dee9548075325ae181b608ba31c55f397bc288875843cc50c089aa4d1f0f8b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f77696e6b2f77696e6b2d6d6f64656c2d67656e657261746f722e737667)](https://packagist.org/packages/wink/wink-model-generator)[![License](https://camo.githubusercontent.com/db7df478e32657dcc688d7aa212ea88eac0e4b3eb7bced7153534189ab68af5a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f77696e6b2f77696e6b2d6d6f64656c2d67656e657261746f722e737667)](https://packagist.org/packages/wink/wink-model-generator)

A focused Laravel package that automatically generates Eloquent models and factories from your existing database schema. For API Resource and Controller generation, check out our companion package [wink-resource-generator](https://github.com/wink-/wink-resource-generator).

Features
--------

[](#features)

- Supports MySQL, PostgreSQL, and SQLite databases (including in-memory SQLite for testing)
- Generates complete model files with proper namespacing and **comprehensive Laravel model properties**
- **Smart property detection**: auto-detects primary keys, key types, incrementing, soft deletes
- **Enhanced security**: automatically hides sensitive fields (passwords, tokens, etc.)
- **Flexible mass assignment**: configurable `$fillable` vs `$guarded` approaches
- **Complete property support**: `$hidden`, `$visible`, `$attributes`, `$with`, `$perPage`, etc.
- Auto-detects relationships from foreign keys
- Configurable model generation options via comprehensive config file
- Generates PHPDoc properties for better IDE support
- Includes validation rules based on schema
- Handles custom database connections
- Optional model factory generation with **automatic exclusion of auto-incremented fields**
- Optional model observer generation
- Connection-based directory structure for multi-database projects
- PSR-4 namespace validation and auto-correction
- Compatible with PHP 8.3+ and Laravel 11+

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

[](#installation)

You can install the package via composer:

```
composer require wink/wink-model-generator --dev
```

Related Packages
----------------

[](#related-packages)

- [wink-resource-generator](https://github.com/wink-/wink-resource-generator) - Generate API Resources, Controllers, and Routes for your Laravel models

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

[](#configuration)

You can publish the configuration file with:

```
php artisan vendor:publish --provider="Wink\ModelGenerator\ModelGeneratorServiceProvider" --tag="config"
```

This will create a `config/model-generator.php` file with comprehensive configuration options:

```
return [
    // Basic configuration
    'default_connection' => 'mysql',
    'excluded_tables' => ['migrations', 'failed_jobs', /* ... */],

    // Model Property Generation Options
    'model_properties' => [
        // Auto-detect primary key from schema instead of hardcoding 'id'
        'auto_detect_primary_key' => true,

        // Generate $hidden array for sensitive fields (password, token, etc.)
        'auto_hidden_fields' => true,
        'hidden_field_patterns' => ['password', 'token', 'secret', 'key', 'hash'],

        // Generate $guarded array (alternative to $fillable)
        'use_guarded_instead_of_fillable' => false,
        'guarded_fields' => ['id', 'created_at', 'updated_at'],

        // Pagination settings
        'per_page' => null, // Set to integer to override default pagination

        // Date format customization
        'date_format' => 'Y-m-d H:i:s', // Laravel default

        // Auto-generate $attributes for default values based on schema
        'auto_default_attributes' => true,

        // Auto-generate $with for common relationships
        'auto_eager_load' => false,
        'eager_load_relationships' => [], // e.g., ['user', 'category']

        // Soft delete detection
        'auto_detect_soft_deletes' => true,

        // Generate $visible array (alternative to $hidden)
        'use_visible_instead_of_hidden' => false,
    ],

    // Custom field type mappings
    'custom_casts' => [
        // Add custom cast mappings here
    ],

    // Validation rules generation
    'validation' => [
        'generate_rules' => true,
        'strict_rules' => false,
        'include_unique_rules' => true,
    ],
];
```

### Model Property Generation

[](#model-property-generation)

The package now automatically generates comprehensive Laravel model properties based on your database schema:

**Smart Detection:**

- **Primary Keys**: Auto-detects from schema instead of hardcoding 'id'
- **Key Types**: Sets `$keyType` to 'string' for UUID/varchar keys, 'int' for integers
- **Incrementing**: Sets `$incrementing = false` for UUID/string primary keys
- **Soft Deletes**: Detects `deleted_at` columns and adds SoftDeletes trait
- **Timestamps**: Detects `created_at`/`updated_at` columns

**Security &amp; Visibility:**

- **Hidden Fields**: Automatically hides sensitive fields matching patterns (password, token, secret, etc.)
- **Visible Fields**: Option to use `$visible` instead of `$hidden`

**Mass Assignment:**

- **Fillable vs Guarded**: Choose between `$fillable` and `$guarded` approaches
- **Smart Exclusions**: Automatically excludes primary keys and timestamps from fillable

**Advanced Properties:**

- **Default Attributes**: Generates `$attributes` array from schema default values
- **Pagination**: Configure custom `$perPage` values
- **Eager Loading**: Auto-generate `$with` for common relationships
- **Date Formatting**: Customize `$dateFormat`

Usage
-----

[](#usage)

The package provides two main commands for generating models and factories.

### Model Generation

[](#model-generation)

Generate Eloquent models from your database schema:

```
# Basic usage
php artisan wink:generate-models

# Common Options
--connection=mysql              # Specify database connection (default: sqlite)
--directory=path/to/models      # Custom output directory for models (absolute or relative to project root)
--factory-directory=path        # Custom output directory for factories (absolute or relative to project root)
--observer-directory=path       # Custom output directory for observers (absolute or relative to project root)
--with-relationships           # Include relationships based on foreign keys
--with-factories              # Generate model factories
--with-observers              # Generate model observers
--with-rules                  # Generate validation rules
--with-scopes                 # Generate query scopes
--with-timestamp-scopes       # Generate timestamp-based scopes
--with-events                 # Generate model event methods
--with-boot-method           # Generate boot method for event registration

# Examples
# Generate models with default directory structure
php artisan wink:generate-models --connection=mysql

# Generate models with custom relative paths (from project root)
php artisan wink:generate-models --connection=pacsys \
  --directory=app/Models/GeneratedModels/Pacsys \
  --factory-directory=database/factories/GeneratedFactories/Pacsys

# Generate models with absolute paths
php artisan wink:generate-models --connection=pacsys \
  --directory=/absolute/path/to/models \
  --factory-directory=/absolute/path/to/factories

# Generate with all features enabled
php artisan wink:generate-models --connection=mysql \
  --with-relationships --with-factories --with-observers \
  --with-rules --with-scopes --with-events
```

### Factory Generation

[](#factory-generation)

When generating factories with `--with-factories`, the package intelligently creates Laravel factories with:

**Smart Field Exclusion:**

- **Auto-incremented fields**: Automatically detects and excludes auto-incremented primary keys
- **Timestamp fields**: Excludes `created_at`, `updated_at`, and `deleted_at` fields
- **Database-specific detection**: Works across MySQL (via `auto_increment`), PostgreSQL (via sequences/identity), and SQLite (via `INTEGER PRIMARY KEY`)

**Generated Factory Features:**

- Business-oriented state methods (`active()`, `inactive()`, `pending()`, `archived()`)
- Test scenario helpers (`forTesting()`, `forDemo()`, `forDevelopment()`)
- Relationship helpers (`withUser()`, `withBusinessMetadata()`)
- Business constraint methods for realistic data generation
- Smart faker method selection based on column names and types

### Directory Structure

[](#directory-structure)

By default, the package organizes generated model files into a `GeneratedModels/{connection_name}` subdirectory. This subdirectory is created within the path defined by the `model_path` configuration option (which defaults to `app/Models`, resulting in a final default path like `app/Models/GeneratedModels/mysql`). A similar structure is used for factories based on the `factory_path` configuration.

The typical default directory structure looks like this:

```
app/
├── Models/
│   └── GeneratedModels/
│       ├── mysql/           # Models for MySQL connection
│       └── sqlite/          # Models for SQLite connection
├── Observers/
│   └── GeneratedObservers/
│       ├── mysql/           # Observers for MySQL connection
│       └── sqlite/          # Observers for SQLite connection
└── database/
    └── factories/
        └── GeneratedFactories/
            ├── mysql/       # Factories for MySQL connection
            └── sqlite/      # Factories for SQLite connection

```

The `--directory` command-line option allows you to specify a custom output directory for models, completely overriding the default `{model_path}/GeneratedModels/{connection_name}` structure. Similarly, the `--factory-directory` and `--observer-directory` options override the defaults for factories and observers. These options accept either absolute paths or paths relative to the project root.

If the relevant directory options are not specified, the defaults are:

- Models: `{model_path}/GeneratedModels/{connection_name}` (e.g., `app/Models/GeneratedModels/mysql` using the default `model_path`)
- Factories: `{factory_path}/GeneratedFactories/{connection_name}` (e.g., `database/factories/GeneratedFactories/mysql` using the default `factory_path`)
- Observers: `{observer_path}/GeneratedObservers/{connection_name}` (e.g., `app/Observers/GeneratedObservers/mysql` using the default `observer_path`)

Recent Improvements
-------------------

[](#recent-improvements)

### Version 1.1.0

[](#version-110)

- **PostgreSQL Support**: Added full support for PostgreSQL databases with auto-increment detection
- **Improved Directory Handling**: Fixed path resolution for relative and absolute directory options
- **Enhanced Help Documentation**: Added comprehensive examples and clearer path requirements
- **Smart Factory Generation**: Factories now automatically exclude auto-incremented fields
- **Better Error Messages**: More helpful error messages for directory permission issues

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

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

###  Health Score

36

—

LowBetter than 81% of packages

Maintenance67

Regular maintenance activity

Popularity7

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 98.1% 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 ~10 days

Recently: every ~36 days

Total

16

Last Release

327d ago

PHP version history (3 changes)v0.1.0PHP ^8.1

v0.2.0PHP ^8.2

v0.4.0PHP ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/259b5afe20523d9a8deb19d5e9d250cce4e21fd58487b38bd52c26f341f11550?d=identicon)[wink-](/maintainers/wink-)

---

Top Contributors

[![wink-](https://avatars.githubusercontent.com/u/1276095?v=4)](https://github.com/wink- "wink- (51 commits)")[![google-labs-jules[bot]](https://avatars.githubusercontent.com/in/842251?v=4)](https://github.com/google-labs-jules[bot] "google-labs-jules[bot] (1 commits)")

---

Tags

laravelschemadatabasegeneratormysqlsqlitemodeleloquent

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/wink-wink-model-generator/health.svg)

```
[![Health](https://phpackages.com/badges/wink-wink-model-generator/health.svg)](https://phpackages.com/packages/wink-wink-model-generator)
```

###  Alternatives

[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[toponepercent/baum

Baum is an implementation of the Nested Set pattern for Eloquent models.

3154.7k](/packages/toponepercent-baum)

PHPackages © 2026

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