PHPackages                             watheqalshowaiter/model-fields - 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. watheqalshowaiter/model-fields

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

watheqalshowaiter/model-fields
==============================

Get model fields fast — required, nullable, or default

3.2.1(6mo ago)40776↓33.3%3[1 PRs](https://github.com/WatheqAlshowaiter/model-fields/pulls)MITPHPPHP &gt;=7.4CI passing

Since Jul 13Pushed 3mo ago4 watchersCompare

[ Source](https://github.com/WatheqAlshowaiter/model-fields)[ Packagist](https://packagist.org/packages/watheqalshowaiter/model-fields)[ Docs](https://github.com/watheqalshowaiter/model-fields)[ GitHub Sponsors](https://github.com/WatheqAlshowaiter)[ RSS](/packages/watheqalshowaiter-model-fields/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (3)Versions (54)Used By (0)

[![Package cover](./arts/package-cover.png)](./arts/package-cover.png)

Model Fields
============

[](#model-fields)

[![Required Laravel Version](https://camo.githubusercontent.com/ad12f0c8a4ddde25be583d748dd3124f1d88e04bb01479be92145352565d72cb/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d254532253839254135362e302d6666326432303f7374796c653d666c61742d737175617265266c6f676f3d6c61726176656c)](https://packagist.org/packages/watheqalshowaiter/model-fields)[![Required PHP Version](https://camo.githubusercontent.com/9ad0de262c273c871b68e817375c4be3a375295b74ec216ac646d3c1c896779a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f776174686571616c73686f7761697465722f6d6f64656c2d6669656c64733f636f6c6f723d253233383839324246267374796c653d666c61742d737175617265266c6f676f3d706870)](https://packagist.org/packages/watheqalshowaiter/model-fields)[![Latest Version on Packagist](https://camo.githubusercontent.com/dfa3e8e7108a6d4071232849d9d7c6f01a1e28b035ffbbc484042de6c8f5770c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f776174686571616c73686f7761697465722f6d6f64656c2d6669656c64732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/watheqalshowaiter/model-fields)[![GitHub Test Matrix Action Status](https://camo.githubusercontent.com/64f5787905c8b1318f7658ca4574266054e347bce549eeb3b5cdd4d3e384620d/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f776174686571616c73686f7761697465722f6d6f64656c2d6669656c64732f746573742d6d61747269782e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/64f5787905c8b1318f7658ca4574266054e347bce549eeb3b5cdd4d3e384620d/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f776174686571616c73686f7761697465722f6d6f64656c2d6669656c64732f746573742d6d61747269782e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/508cad92d805324c17808962787a35290089ebdab9de31bf9d13e1bdbd8c284c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f776174686571616c73686f7761697465722f6d6f64656c2d6669656c64732f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/508cad92d805324c17808962787a35290089ebdab9de31bf9d13e1bdbd8c284c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f776174686571616c73686f7761697465722f6d6f64656c2d6669656c64732f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)[![Total Downloads](https://camo.githubusercontent.com/408473fb86ee292ec737dcaff6bd1f9801d7e972838fabe0ee351343d928b74f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f776174686571616c73686f7761697465722f6d6f64656c2d6669656c64732e7376673f7374796c653d666c61742d73717561726526636f6c6f723d253233303037656336)](https://packagist.org/packages/watheqalshowaiter/model-fields/stats)[![GitHub Stars](https://camo.githubusercontent.com/b354d4729c3f5b3f7bef5cba11cf39908ffea21032b54c18a16ad0c8c648f15a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f776174686571616c73686f7761697465722f6d6f64656c2d6669656c64733f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/b354d4729c3f5b3f7bef5cba11cf39908ffea21032b54c18a16ad0c8c648f15a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f776174686571616c73686f7761697465722f6d6f64656c2d6669656c64733f7374796c653d666c61742d737175617265)[![StandWithPalestine](https://raw.githubusercontent.com/TheBSD/StandWithPalestine/main/badges/StandWithPalestine.svg)](https://github.com/TheBSD/StandWithPalestine/blob/main/docs/README.md)[![ko-fi](https://camo.githubusercontent.com/5e00067f5e4735d985d5936c33169a33b63c243a2f336dbdcc03c20f275b3320/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4b6f2d2d66692d537570706f72742d6666356635663f6c6f676f3d6b6f2d6669267374796c653d666c61742d737175617265)](https://ko-fi.com/watheq_show)

Quickly retrieve **required**, **nullable**, and **default** fields for any Laravel model. Think that's simple? You probably haven’t faced the legacy projects I have. :).

Note

This is the documentation for version 3, if you want the version 1 or version 2 documentations go
V2 with [this link](./v2.documentation.md).
V1 with [this link](./v1.documentation.md).

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

[](#installation)

You can install the package via Composer:

```
composer require watheqalshowaiter/model-fields --dev
```

We prefer `--dev` because you usually use it in development, not in production. If you have a use case that requires using the package in production, then remove the --dev flag.

Optionally, if you want to publish the configuration to disable/enable model macros.

```
php artisan vendor:publish --provider="WatheqAlshowaiter\ModelFields\ModelFieldsServiceProvider" --tag="config"
```

Usage
-----

[](#usage)

We Assume that the `User` model has this schema as the default.

```
Schema::create('users', function (Blueprint $table) {
    $table->id(); // primary key
    $table->string('name'); // required
    $table->string('email')->unique(); // required
    $table->timestamp('email_verified_at')->nullable(); // nullable
    $table->string('password'); // required
    $table->string('random_number'); // default (in model attributes)
    $table->rememberToken(); // nullable
    $table->timestamps(); // nullable
});
```

Important

We have two ways:

- Either use the `ModelFields` facade.
- Or use the method statically on the model. (using the magic of laravel macros).
- Or use the `model:fields` console command.

Here is the sample:

```
// Facade way
use WatheqAlshowaiter\ModelFields\Fields;
use App\Models\User;

Fields::model(User::class)->allFields(); // returns ['id', 'name', 'email', 'email_verified_at', 'password', 'random_number', 'remember_token', 'created_at', 'updated_at']
Fields::model(User::class)->requiredFields(); // returns ['name', 'email', 'password']
```

```
// Macro way
User::allFields(); // returns ['id', 'name', 'email', 'email_verified_at', 'password', 'random_number', 'remember_token', 'created_at', 'updated_at']
User::requiredFields(); // returns ['name', 'email', 'password']
```

```
# console command
php artisan model:fields \\App\\Models\\User --all --format=json
php artisan model:fields "App\Models\User" --required --format=table
```

That's it!

Note

To disable the macro approach, set the `enable_macro` value to false in the published `model-fields.php`configuration file.

### Another Complex Table

[](#another-complex-table)

Let's say the `Post` model has these fields

```
Schema::create('posts', function (Blueprint $table) {
    $table->uuid('id')->primary(); // primary key
    $table->foreignId('user_id')->constrained(); // required
    $table->foreignId('category_id')->nullable(); // nullable
    $table->uuid(); // required (but will be changed later) 👇
    $table->ulid('ulid')->nullable(); // nullable (but will be changed later) 👇
    $table->boolean('active')->default(false); // default
    $table->string('title'); // required
    $table->json('description')->nullable(); // nullable (but will be changed later) 👇
    $table->string('slug')->nullable()->unique(); // nullable
    $table->timestamps(); // nullable
    $table->softDeletes(); // nullable
});

// later migration..
Schema::table('posts', function(Blueprint $table){
    $table->json('description')->nullable(false)->change(); // required
    $table->ulid('ulid')->nullable(false)->change(); // required
    $table->uuid()->nullable()->change(); // nullable
});
```

```
// Facade way
Fields::model(Post::class)->requiredFields(); // returns ['user_id', 'ulid', 'title', 'description']
// Macro way
Post::requiredFields();  // returns ['user_id', 'ulid', 'title', 'description']
```

```
# console command
php artisan model:fields App\\Models\\Post --required # or -r
```

#### Observer and Event-Filled Fields

[](#observer-and-event-filled-fields)

Fields that are automatically filled when creating by model observers, boot events, and event listeners are automatically excluded from required fields.

The package supports three patterns:

- **Boot method closures:** `self::creating()`, `self::saving()`
- **Observer pattern:** `PostObserver` class
- **Dispatched events:** `$dispatchesEvents` property

For example, given this model:

```
class Post extends Model
{
    protected $dispatchesEvents = [
        // a dispatched event trigger listener that fills the `user_id` field
        'creating' => PostCreatingEvent::class,
    ];

    protected static function boot()
    {
        parent::boot();
        self::observe(PostObserver::class);

        self::creating(function ($model) {
            $model->ulid = Str::ulid();
        });

        self::saving(function ($model) {
            $model->title = 'default title'
        });
    }
}

class PostObserver
{
    public function creating(Post $model): void
    {
        $model->description = 'default description';
    }

    public function saving(Post $model): void
    {
        $model->description = 'default saving description';
    }
}
```

```
Post::requiredFields();

// returns [] because it excludes auto-filled fields
```

### And more

[](#and-more)

We have the flexibility to get all fields, required fields, nullable fields, primary key, database default fields, application default fields, and default fields. You can use these methods with these results:

#### All fields

[](#all-fields)

```
Fields::model(Post::class)->allFields();

// or
Post::allFields();

// returns
// [    'category_id', 'uuid', 'ulid', 'description',
//      'slug', 'created_at', 'updated_at', 'deleted_at'
// ]
```

```
php artisan model:fields App\\Models\\Post --all # or just the model without option because it is the default
```

#### Nullable fields

[](#nullable-fields)

```
Fields::model(Post::class)->nullableFields();

//or
Post::nullableFields();

// returns
// [
//     'category_id', 'uuid', 'slug',
//     'created_at', 'updated_at', 'deleted_at'
// ]
```

```
# console command
php artisan model:fields App\\Models\\Post --nullable    # or -N
```

#### Primary field

[](#primary-field)

```
Fields::model(Post::class)->primaryField();

// or
Post::primaryField();

// returns ['id']
```

```
# console command
php artisan model:fields User --primary     # or -p
```

#### Database default fields

[](#database-default-fields)

```
Fields::model(Post::class)->databaseDefaultFields();

//or
Post::databaseDefaultFields();

// returns ['active']
```

```
# console command
php artisan model:fields User --db-default  # or -D
```

#### Application default fields

[](#application-default-fields)

```
Fields::model(Post::class)->applicationDefaultFields();

//or
Post::applicationDefaultFields();

// If there are default attributes in the model
class Post extends Model
{
    protected $attributes = [
        'title' => 'default title',
        'description' => null, // will be ignored
    ];

     protected $dispatchesEvents = [
        // if there is a field autofilled by this event,
        // then it will be added to the application default fields
        'creating' => PostCreatingEvent::class,
    ];

    // or any event-filled fields
     protected static function boot(): void
    {
        parent::boot();
        self::observe(PostObserver::class);

        self::creating(function ($model) {
            $model->uuid = Str::uuid();
        });

        self::saving(function ($model) {
            $model->ulid = Str::ulid();
        });
    }
}

// the same in the observer class
class PostObserver
{

    public function creating(Post $model): void
    {
        // ..
    }

    public function saving(Post $model): void
    {
        // ..
    }
}

// returns
// [
//     'title', 'uuid', 'ulid',
// ]
```

```
#console command
php artisan model:fields User --app-default # or -A
```

#### Default fields

[](#default-fields)

```
Fields::model(Post::class)->defaultFields();

//or
Post::defaultFields();

// This will combine application and database defaults
class Post extends Model
{
    protected $attributes = [
        'title' => 'default title',
    ];

    protected static function boot(): void
    {
        parent::boot();

        self::creating(function ($model) {
            $model->description = 'default description';
        });
    }
}

// returns
// [
//    'active', 'title', 'description',
// ]
```

```
#console command
php artisan model:fields User --default     # or -d
```

### More on console commands

[](#more-on-console-commands)

- All fields is the default option if you didn't specify one.

```
php artisan model:fields \\App\\Models\\Post # will result all fields
```

- The package will try to find models in common places if you don't provide full namespace.

```
php artisan model:fields User # It will try to find the model in `App\Models\User` or `App\User` namespaces
```

- You can add namespaces in two ways: in two backslashes `\\` or inside double quotes `""`. This is a laravel thing and not specific to the package.

```
php artisan model:fields \\Modules\\Order\\src\\Models\\Order
# or
php artisan model:fields "Modules\Order\src\Models\Order"
```

- You have 3 output formats: list, json, and table. the list is the default

```
php artisan model:fields User --format=json
php artisan model:fields User --format=table
php artisan model:fields User --format=list  # default
```

Why?
----

[](#why)

### The problem

[](#the-problem)

I wanted to add tests to a legacy project that didn't have any. I wanted to add tests but couldn't find a factory, so I tried building them. However, it was hard to figure out the required fields for testing the basic functionality since some tables have too many fields across many migration files.

### The Solution

[](#the-solution)

To solve this, I first created a simple facade class and a trait (which was later removed) to allow direct method usage on models for retrieving required fields. Later, I added support for older Laravel versions, as most use cases were on those versions.

So Briefly, This package is useful if:

- you want to build factories or tests for projects you didn't start from scratch.
- you are working with a legacy project and don't want to be faced with SQL errors when creating tables.
- you have so many fields in your table and want to get types of fields fast, like required, nullable, default fields.
- or any use case you find it useful.

Features
--------

[](#features)

✅ Supports Laravel versions: 12, 11, 10, 9, 8, 7, and 6.

✅ Supports PHP versions: 8.4, 8.3, 8.2, 8.1, 8.0, and 7.4.

✅ Supports multiple ways of fetching fields: using console commands, or facades, or models macros.

✅ Supports SQL databases: SQLite, MySQL/MariaDB, PostgreSQL, and SQL Server.

✅ Fully automated tested with PHPUnit.

✅ Full GitHub Action CI pipeline to format code and test against all Laravel and PHP versions.

✅ Can return fields based on the dynamically added class strings (in the facade method).

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

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

[](#contributing)

If you have any ideas or suggestions to improve it or fix bugs, your contribution is welcome.

I encourage you to look at [Issues](https://github.com/WatheqAlshowaiter/model-fields/issues) which are the most important features that need to be added.

If you have something different, submit an issue first to discuss or report a bug, then do a pull request.

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

[](#security-vulnerabilities)

If you find any security vulnerabilities don't hesitate to contact me at `watheqalshowaiter[at]gmail[dot]com` to fix them.

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

[](#related-packages)

- **[Backup Tables](https://github.com/WatheqAlshowaiter/backup-tables)** - Backup single or multiple database tables with ease.
- **[Filament Sticky Table Header](https://github.com/WatheqAlshowaiter/filament-sticky-table-header)** - Make Filament table headers stick when scrolling for better UX.

Support this project
--------------------

[](#support-this-project)

If this project helps you, consider supporting it on [Ko-fi ☕](https://ko-fi.com/watheq_show).

Credits
-------

[](#credits)

- [Watheq Alshowaiter](https://github.com/WatheqAlshowaiter)
- [All Contributors](https://github.com/WatheqAlshowaiter/model-fields/graphs/contributors)

License
-------

[](#license)

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

###  Health Score

46

—

FairBetter than 93% of packages

Maintenance76

Regular maintenance activity

Popularity30

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 97.3% 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 ~14 days

Recently: every ~9 days

Total

34

Last Release

183d ago

Major Versions

1.16.0 → 2.0.02025-03-15

2.0.0 → 3.0.02025-09-18

PHP version history (2 changes)1.3.0PHP ^8.2

1.4.0PHP &gt;=7.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/46733da79a34ff686b036a09af1dcc6d21054aee25a5e029500dc87d3c69ba89?d=identicon)[WatheqAlshowaiter](/maintainers/WatheqAlshowaiter)

---

Top Contributors

[![WatheqAlshowaiter](https://avatars.githubusercontent.com/u/24838274?v=4)](https://github.com/WatheqAlshowaiter "WatheqAlshowaiter (355 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (5 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (5 commits)")

---

Tags

laravellaravel-packagemodelmysqlphpphp-packagepostgresqlsqlsqlitesqlserveryemenopensourcephplaravelpackagemysqlsqlitepostgresqlmariadbsqlsqlservermodelWatheqAlshowaiterWatheq Alshowaiterphp-packageyemenopensourceyemen\_open\_sourcemodel-fields

### Embed Badge

![Health badge](/badges/watheqalshowaiter-model-fields/health.svg)

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

###  Alternatives

[doctrine/dbal

Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management.

9.7k578.4M5.6k](/packages/doctrine-dbal)[ramadan/easy-model

A Laravel package for enjoyably managing database queries.

101.6k](/packages/ramadan-easy-model)[aura/sqlschema

Provides facilities to read table names and table columns from a database using PDO.

41234.1k4](/packages/aura-sqlschema)[moharrum/laravel-adminer

Adminer database management tool for your Laravel application.

451.0k](/packages/moharrum-laravel-adminer)

PHPackages © 2026

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