Weave 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

Eloquence Validable Laravel Package

sofa/eloquence-validable

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sofa/eloquence-validable
    

    Add the trait to your Eloquent model:

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

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

    $user = new User(['name' => 'John', 'email' => 'invalid-email']);
    if ($user->isValid()) {
        $user->save(); // Only saves if valid
    } else {
        // Handle errors: $user->errors()
    }
    

Where to Look First

  • rules() method: Core validation logic.
  • errors() method: Access validation error messages.
  • isValid() method: Check if the model passes validation.
  • validate() method: Explicitly trigger validation.

Implementation Patterns

Core Workflows

1. Basic Validation

// Validate on creation/update
$user = new User(['name' => 'Jane']);
if ($user->isValid()) {
    $user->save();
}

// Validate existing record
$user->name = 'Updated Name';
$user->validate(); // Re-validate

2. Conditional Rules

Use rules() dynamically with closures:

protected function rules(): array
{
    return [
        'email' => function ($email) {
            return $email ? 'required|email' : 'nullable';
        },
    ];
}

3. Custom Error Messages

Override messages():

protected function messages(): array
{
    return [
        'name.required' => 'The name field is mandatory!',
    ];
}

4. Validation on Query Results

Validate collections or single models:

$users = User::where('active', true)->get()->filter->isValid();

5. Integration with Forms

Use with Laravel's Form Requests or frontend validation:

// In a FormRequest
public function rules()
{
    return (new User())->rules(); // Reuse model rules
}

6. Custom Validation Logic

Extend with validateCustom():

protected function validateCustom()
{
    if ($this->age < 18) {
        $this->errors()->add('age', 'Must be at least 18.');
    }
}

Integration Tips

With API Resources

Validate before serialization:

public function toArray($request)
{
    $this->validate();
    return [
        'data' => $this->only(['name', 'email']),
    ];
}

With Observers

Validate in saving/updating:

public function saving(Model $model)
{
    if (!$model->isValid()) {
        throw new \Exception('Validation failed');
    }
}

With API Tests

Assert validation errors:

$response = $this->post('/users', ['email' => 'invalid']);
$response->assertJsonValidationErrors(['email']);

Gotchas and Tips

Pitfalls

  1. Rule Overrides:

    • If extending a model, ensure rules() is merged, not overwritten:
      protected function rules(): array
      {
          return array_merge(parent::rules(), [
              'new_field' => 'required',
          ]);
      }
      
  2. Lazy Validation:

    • isValid() runs rules only when called. For eager validation, use validate() explicitly.
  3. Mass Assignment:

    • Unsafe mass assignment can bypass validation. Use $fillable or $guarded carefully.
  4. Custom Logic Timing:

    • validateCustom() runs after rule validation. Use it for post-validation checks.
  5. Nested Model Validation:

    • For nested models (e.g., User::with('posts')->get()), validate each manually:
      $user->posts->each->validate();
      

Debugging Tips

  1. Inspect Errors:

    dd($model->errors()->all());
    
  2. Disable Rules Temporarily:

    $model->setRules([]); // Clear rules
    
  3. Check Rule Sources:

    • Rules can come from:
      • Model’s rules() method.
      • Parent traits/classes.
      • Laravel’s global rules (e.g., FormRequest).
  4. Validate Partial Data:

    $model->validate(['name' => 'Test']); // Validate specific fields
    

Extension Points

  1. Custom Validators: Add reusable validators to the model:

    protected function customValidators(): array
    {
        return [
            'unique_username' => function ($username) {
                return User::where('username', $username)->exists()
                    ? 'Username taken'
                    : null;
            },
        ];
    }
    
  2. Dynamic Rule Generation: Use closures for context-aware rules:

    protected function rules(): array
    {
        return [
            'password' => function ($password, $model) {
                return $model->exists
                    ? 'sometimes|string|min:8'
                    : 'required|string|min:8';
            },
        ];
    }
    
  3. Event-Based Validation: Trigger validation on events:

    $model->on('validating', function ($model) {
        // Pre-validation logic
    });
    
  4. Override Validation Logic: Extend the trait to modify behavior:

    trait CustomValidable
    {
        public function validate()
        {
            // Custom logic
            parent::validate();
        }
    }
    

Config Quirks

  • No Config File: All behavior is code-driven (no config/eloquence.php).
  • Rule Prioritization: Later rules in rules() override earlier ones for the same field.
  • Error Handling: Errors are stored in Laravel’s default Validator instance. Use errors() to access them.
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.
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator