watheqalshowaiter/model-fields

Get model fields fast β€” required, nullable, or default


README

Package cover

Model Fields

Required Laravel Version Required PHP Version Latest Version on Packagist GitHub Tests For Laravel Versions Action Status GitHub Tests For Databases Action Status GitHub Code Style Action Status Total Downloads GitHub Stars StandWithPalestine

Get the required fields fast for any model. You can also get nullable and default fields just as easily. 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.
V1 with this link.

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

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

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

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

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

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

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

// or
Post::primaryField();

// returns ['id']
# console command
php artisan model:fields User --primary     # or -p

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

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

//or 
Post::applicationDefaultFields();

// If there is default attributes in the model
class Post extends Model
{
    protected $attributes = [
        'title' => 'default title', 
        'description' => 'default description',
    ];
}

// returns
// [
//     'title', 'description',
// ]
#console command
php artisan model:fields User --app-default # or -A

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', 
        'description' => 'default description',
    ];
}

// returns
// [
//    'active', 'title', 'description',
// ]
#console command
php artisan model:fields User --default     # or -d

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?

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

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

βœ… 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

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

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 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

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

Credits

License

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