Looking to hire Laravel developers? Try LaraJobs

laravel-auto-validator maintained by weloveahmed

Description
Automatic validation rules generation for Laravel Eloquent models based on database schema.
Author
Last update
2026/01/16 10:36 (dev-main)
License
Links
Downloads
1

Comments
comments powered by Disqus

Laravel Auto Validator

Latest Version on Packagist Total Downloads License

Automatic validation rules generation for any Eloquent model based on database schema introspection.


✨ Why this package?

Laravel validation is powerful, but writing FormRequests for every model/table can become repetitive.

This package automatically generates validation rules based on your database schema:

  • Column types
  • Length constraints
  • Required vs nullable
  • Unique indexes
  • Foreign keys (exists rules)

Then allows you to customize and extend rules using:

  • Model overrides
  • Reusable profiles
  • Multi-tenant constraints
  • SoftDeletes-aware uniqueness
  • JSON deep validation (nested rules)

✅ Features

  • Schema Introspection: Generate rules from column types, lengths, nullability, unique indexes, and foreign keys.
  • Context-Aware: Supports store and update contexts (handles unique ignore automatically).
  • Overrides: Model-specific overrides via simple PHP files.
  • Profiles: Reusable validation templates (e.g. person, address, api-mobile).
  • SoftDeletes Aware: Unique rules can ignore soft-deleted rows.
  • Multi-Tenant Ready: Add tenant constraints to unique and exists.
  • JSON Support: Map JSON columns to arrays and validate nested fields.
  • Performance: Caching of schema and generated rules.
  • Developer Experience: Fluent API + optional Artisan generators.

📦 Installation

composer require weloveahmed/laravel-auto-validator

Laravel auto-discovers the Service Provider.

⚙️ Configuration

Publish the config file:

php artisan vendor:publish --tag=auto-validator-config

Config file location: config/auto-validator.php

return [
    'ignore_columns' => [
        'id',
        'created_at',
        'updated_at',
        'deleted_at',
    ],
    'cache' => [
        'enabled' => true,
        'store' => env('AUTO_VALIDATOR_CACHE_STORE', null),
        'ttl' => 3600,
        'prefix' => 'auto_validator:',
    ],
    'overrides_path' => app_path('AutoValidation'),
    'profiles' => [
        // 'person' => [
        //     'name' => ['required', 'string', 'max:255'],
        // ]
    ],
];

⚡ How it works (Internals)

The package follows a simple pipeline:

SchemaReader → RuleMapper → RuleFactory → Overrides → Profiles → Context

🚀 Basic Usage

This package is designed to work with any Eloquent model.

✅ Generate Store Rules

use Weloveahmed\AutoValidator\Facades\AutoValidator;

$rules = AutoValidator::for(Employee::class)
    ->store()
    ->rules();

✅ Validate Store Data

$data = AutoValidator::for(Employee::class)
    ->store()
    ->validate(request()->all());

✅ Generate Update Rules

$rules = AutoValidator::for(Employee::class)
    ->update($employee->id)
    ->rules();

✅ Validate Update Data

$data = AutoValidator::for(Employee::class)
    ->update($employee->id)
    ->validate(request()->all());

🧩 Model Overrides

Create a file: app/AutoValidation/Employee.php

return [
    'email' => ['required', 'email'],
    'mobile' => ['nullable', 'regex:/^(01)[0-9]{9}$/'],
];

🧠 Profiles (Reusable Rule Sets)

Define profiles in config:

'profiles' => [
    'api-mobile' => [
        'mobile' => ['required', 'regex:/^(01)[0-9]{9}$/'],
    ],
],

Apply profile:

$rules = AutoValidator::for(Employee::class)
    ->profile('api-mobile')
    ->store()
    ->rules();

🏢 Multi-Tenancy Support

Implement TenantResolver:

use Weloveahmed\AutoValidator\Contracts\TenantResolver;

class MyTenantResolver implements TenantResolver
{
    public function enabled(): bool { return true; }
    public function tenantId(): mixed { return tenant('id'); }
    public function tenantKeyName(): string { return 'tenant_id'; }
}

Bind it in your AppServiceProvider:

$this->app->bind(TenantResolver::class, MyTenantResolver::class);

🗑 SoftDeletes-Aware Unique Rules

Only needed if your model uses SoftDeletes.

AutoValidator::for(Employee::class)
    ->store()
    ->softDeletes()
    ->rules();

🧾 JSON Deep Validation

To validate nested JSON data, add overrides:

return [
    'grades' => ['nullable', 'array'],
    'grades.*.year' => ['required', 'integer'],
    'grades.*.percentage' => ['required', 'numeric', 'min:0', 'max:100'],
];

📦 Bulk Import (Enterprise Feature)

$results = AutoValidator::for(Employee::class)
    ->store()
    ->bulk()
    ->validateRows($rows);

$validatedRows = $results->validated();
$errors = $results->errors();

🛠 Artisan Commands

php artisan autovalidator:request Employee
php artisan autovalidator:override Employee
php artisan autovalidator:profile person

✅ Testing

composer test

✅ Compatibility

PHP: 8.2+ Laravel: 10+

🔐 Security

If you discover any security issues, please email: zinorsro2013@gmail.com

🤝 Contributing

Contributions are welcome! Submit PRs with tests.

📄 License

MIT License. See LICENSE.md