Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Schema Rules Laravel Package

laracraft-tech/laravel-schema-rules

Generate basic Laravel validation rules from your database schema. Create rules for entire tables or selected columns, scaffold Form Request classes, and configure columns to always skip. Great as a starting point to refine and optimize validation.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laracraft-tech/laravel-schema-rules --dev
    php artisan vendor:publish --tag="schema-rules-config"
    

    Verify the config file is published to config/schema-rules.php.

  2. First Use Case: Generate validation rules for an existing table (e.g., users):

    php artisan schema:generate-rules users
    

    Output will be a JSON array of validation rules for each column, ready to paste into your controller or Form Request.


Where to Look First

  • Artisan Command: php artisan schema:generate-rules --help to explore all flags.
  • Config File: config/schema-rules.php for customizing skipped columns or default behavior.
  • Web Demo: validationforlaravel.com for interactive testing.

Implementation Patterns

Workflow: Generating Rules for a New Table

  1. Create Migration: Define your table schema (e.g., users).
  2. Run Migration: php artisan migrate.
  3. Generate Rules:
    php artisan schema:generate-rules users
    
    Copy the output into your StoreUserRequest or controller validation.

Workflow: Integrating with Form Requests

  1. Generate a Form Request class directly:

    php artisan schema:generate-rules users --create-request --file StoreUserRequest
    

    This creates app/Http/Requests/StoreUserRequest.php with pre-filled rules.

  2. Customize the Request: Extend the generated class to add custom logic:

    public function rules()
    {
        $rules = parent::rules(); // Inherit schema rules
        $rules['email'][] = 'unique:users'; // Add custom rule
        return $rules;
    }
    

Workflow: Partial Rule Generation

Generate rules for specific columns (e.g., name and email):

php artisan schema:generate-rules users --columns name,email

Workflow: API-Specific Requests

Create a request for an API namespace:

php artisan schema:generate-rules users --create-request --file Api\\V1\\StoreUserRequest

Integration Tips

  1. Use in Controllers:

    public function store(Request $request)
    {
        $validated = $request->validate(
            $this->generateSchemaRules('users') // Assume this method calls the artisan command
        );
    }
    
  2. Combine with Custom Rules: Override generated rules in your Form Request:

    public function rules()
    {
        $schemaRules = $this->getSchemaRules('users');
        return array_merge($schemaRules, [
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }
    
  3. Dynamic Rule Generation: Create a helper method in a trait or service:

    public function getSchemaRules(string $table): array
    {
        $command = new GenerateRulesCommand();
        return $command->getRules($table);
    }
    
  4. Testing: Use the generated rules in PHPUnit tests:

    public function test_validation()
    {
        $rules = $this->getSchemaRules('users');
        $validator = Validator::make($data, $rules);
        $validator->validate();
    }
    

Gotchas and Tips

Pitfalls

  1. Floating-Point Precision: The package generates ['numeric'] for float, decimal, and double columns. For precise validation, manually add rules like ['numeric', 'min:0.00', 'max:100.00'].

  2. Driver-Specific Quirks:

    • MySQL: May generate max:255 for string columns (adjust if needed).
    • PostgreSQL: jsonb columns generate ['json'] rules.
    • SQLite: May have inconsistent length limits for string columns.
  3. Foreign Key Validation: The package generates exists:table,column rules, but ensure the referenced table exists and the column matches.

  4. Nullable Fields: The package adds ['nullable'] for nullable columns, but be cautious with required rules in Form Requests. Use sometimes or conditional validation if needed:

    public function rules()
    {
        $rules = $this->getSchemaRules('users');
        $rules['bio'] = array_filter($rules['bio'], fn($rule) => $rule !== 'nullable');
        return $rules;
    }
    
  5. Config Overrides: If you skip columns in config/schema-rules.php, ensure they are excluded from migrations or handled separately (e.g., deleted_at for soft deletes).


Debugging

  1. Check Column Types: If rules seem incorrect, verify the column type in your migration or database schema:

    php artisan schema:show users
    
  2. Artisan Verbosity: Use -v or -vv flags to debug:

    php artisan schema:generate-rules users -vv
    
  3. Custom Rule Logic: Extend the package by publishing and modifying its service provider or command. Override the getRules method in GenerateRulesCommand.


Tips

  1. Skip Timestamps: The config defaults to skip created_at, updated_at, and deleted_at. Add more to skip_columns if needed:

    'skip_columns' => [
        'created_at',
        'updated_at',
        'deleted_at',
        'user_id', // Custom skip
    ],
    
  2. Web Interface: Use validationforlaravel.com to preview rules before generating them.

  3. CI/CD Integration: Add the command to your deployment pipeline to ensure validation rules stay in sync with the schema:

    # .github/workflows/deploy.yml
    - run: php artisan schema:generate-rules users --create-request
    
  4. Partial Overrides: Generate rules once, then manually tweak them in your Form Request:

    public function rules()
    {
        return array_merge(
            $this->getSchemaRules('users'),
            ['email' => ['unique:users']]
        );
    }
    
  5. Laravel 11+ Compatibility: The package supports Laravel 11–13. For older versions, pin to v1.3.x or earlier.

  6. Performance: Avoid generating rules on every request. Cache the output or regenerate only during migrations:

    $rules = cache()->remember("schema-rules-{$table}", now()->addHours(1), fn() =>
        $this->getSchemaRules($table)
    );
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony