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

Validating Laravel Package

watson/validating

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require watson/validating
    

    Add the trait to your Eloquent model:

    use Watson\Validating\Validating;
    
    class User extends Model
    {
        use Validating;
    }
    
  2. Define Validation Rules: Override the rules() method in your model:

    protected function rules()
    {
        return [
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
        ];
    }
    
  3. First Use Case: Save a model instance—validation runs automatically:

    $user = new User(['name' => 'John', 'email' => 'invalid-email']);
    $saved = $user->save(); // Returns false if validation fails
    

Key Starting Points

  • rules(): Core method for defining validation rules.
  • validate(): Manually trigger validation (returns true/false).
  • validateOnly(): Validate specific fields without saving.
  • errors(): Access validation error messages.

Implementation Patterns

Core Workflows

  1. Basic Validation on Save:

    $user = new User(['email' => 'test@example.com']);
    if ($user->save()) {
        // Success: model saved
    } else {
        // Fail: errors available via $user->errors()
    }
    
  2. Dynamic Rules (Conditional Validation): Use rules() with closures or override rules() dynamically:

    protected function rules()
    {
        return [
            'email' => function ($field) {
                return $this->isAdmin()
                    ? 'required|email'
                    : 'nullable|email';
            },
        ];
    }
    
  3. Rule Sets (Multi-Validation Scenarios): Define named rule sets in rules() and validate them explicitly:

    protected function rules()
    {
        return [
            'admin' => [
                'email' => 'required|email',
                'role'  => 'in:admin,superadmin',
            ],
            'user' => [
                'email' => 'required|email',
            ],
        ];
    }
    
    // Validate 'admin' ruleset
    $user->validate('admin');
    
  4. Unique Validation with Model ID: Automatically injects the model's ID into unique rules (e.g., unique:users,email,{$id}):

    'email' => 'required|email|unique:users,email',
    
  5. Custom Validation Logic: Extend the trait or use Laravel’s validation callbacks:

    protected function validateCustomRules()
    {
        $this->validateCustom('password', function ($field) {
            return strlen($field) >= 8;
        }, 'Password must be at least 8 characters.');
    }
    

Integration Tips

  • Form Requests: Use alongside Laravel’s FormRequest for API/controller validation.
  • API Responses: Attach errors to API responses:
    return response()->json(['errors' => $model->errors()], 422);
    
  • Events: Trigger custom events on validation failure:
    protected function onValidationFailed()
    {
        event(new ModelValidationFailed($this));
    }
    
  • Testing: Mock validation in unit tests:
    $user = new User(['email' => 'invalid']);
    $user->shouldReceive('validate')->andReturn(false);
    

Gotchas and Tips

Pitfalls

  1. Rule Set Mismatches:

    • Issue: Forgetting to specify a rule set when calling validate('ruleset').
    • Fix: Ensure rule sets are defined in rules() and referenced correctly.
  2. Overriding save():

    • Issue: Custom save() methods may bypass the trait’s validation.
    • Fix: Call $this->validate() explicitly or use parent::save().
  3. Dynamic Rules Timing:

    • Issue: Rules using $this-> properties (e.g., $this->isAdmin()) may fail if accessed too early.
    • Fix: Use closures or lazy-evaluate properties.
  4. Unique Rule ID Injection:

    • Issue: unique rules with dynamic IDs may fail if the model lacks an ID (e.g., during creation).
    • Fix: Use unique:table,column,null,id,field for "ignore null" cases.
  5. Error Handling:

    • Issue: Silent failures if save() is called without checking its return value.
    • Fix: Always check $model->save() or use try-catch with exceptions:
      try {
          $model->save();
      } catch (\Exception $e) {
          // Handle validation exceptions
      }
      

Debugging Tips

  • Inspect Rules: Dump the active rules with:
    dd($this->getRules());
    
  • Validate Manually: Test rules independently:
    $validator = $this->getValidator(['field' => 'value']);
    
  • Check for Overrides: Ensure no other traits/methods interfere with save() or validate().

Extension Points

  1. Custom Validation Logic: Override validateCustomRules() to add field-specific checks.

  2. Exception Handling: Extend the trait to throw custom exceptions:

    protected function onValidationFailed()
    {
        throw new \InvalidArgumentException('Custom error message');
    }
    
  3. Rule Sets: Dynamically generate rule sets based on model state:

    protected function rules()
    {
        return [
            'active' => $this->isActive() ? ['field' => 'required'] : [],
        ];
    }
    
  4. Integration with Policies: Combine with Laravel’s authorization:

    if ($this->authorize('update', $model)) {
        $model->validate();
    }
    
  5. Mass Assignment: Use fillable/guarded alongside validation to control allowed fields:

    protected $fillable = ['name', 'email'];
    
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.
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed