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

Validation Laravel Package

cakephp/validation

Lightweight validation library from the CakePHP ecosystem. Define rules and validators for arrays and data objects, run checks, and collect readable error messages. Useful standalone or within CakePHP apps for consistent input validation.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Installation Add the package via Composer:

    composer require cakephp/validation
    
  2. Basic Usage Import the validator and define rules in a Laravel service or controller:

    use Cake\Validation\Validator;
    
    $validator = new Validator();
    $validator->add('email', 'custom', [
        'rule' => 'email',
        'message' => 'Invalid email format'
    ]);
    
  3. First Use Case: Form Validation Validate user input in a Laravel request handler:

    $data = ['email' => 'test@example.com'];
    $errors = $validator->validate($data);
    if (!empty($errors)) {
        // Handle validation errors (e.g., return JSON response)
    }
    
  4. Key Files to Explore

    • src/Validator.php (Core validation logic)
    • src/Validation.php (Validation rules and helpers)
    • tests/ (Test cases for edge cases and rules)

Implementation Patterns

1. Rule-Based Validation

Define reusable validation rules in a dedicated class:

class UserValidator extends Validator {
    public function __construct() {
        $this->add('username', 'notEmpty', [
            'rule' => 'notEmpty',
            'message' => 'Username cannot be empty'
        ]);
        $this->add('password', 'length', [
            'rule' => ['minLength', 8],
            'message' => 'Password must be at least 8 characters'
        ]);
    }
}

2. Integration with Laravel Forms

Use in Laravel's FormRequest or manually in controllers:

public function validateCustom(Request $request) {
    $validator = new UserValidator();
    $data = $request->all();
    $errors = $validator->validate($data);
    if ($errors) {
        return response()->json($errors, 422);
    }
    // Proceed with logic
}

3. Custom Rules

Extend the validator with custom rules:

$validator->add('custom_field', 'customRule', [
    'rule' => function ($value) {
        return str_contains($value, 'admin');
    },
    'message' => 'Field contains restricted text'
]);

4. Batch Validation

Validate multiple datasets (e.g., bulk imports):

$validator = new Validator();
$validator->add('name', 'notEmpty');
$validator->add('age', 'range', ['min' => 18]);

$users = [
    ['name' => 'John', 'age' => 25],
    ['name' => '', 'age' => 17]
];

$results = array_map(function ($user) use ($validator) {
    return $validator->validate($user);
}, $users);

5. Laravel Service Provider Integration

Bind the validator to Laravel's container for dependency injection:

// In AppServiceProvider
$this->app->bind(Validator::class, function () {
    return new Validator();
});

Gotchas and Tips

Pitfalls

  1. No Laravel-Specific Features

    • The package lacks Laravel-specific integrations (e.g., Validator facade, FormRequest hooks). Manual error handling is required.
    • Example: No built-in translation support for messages (use Laravel's trans() helper manually).
  2. Rule Naming Conflicts

    • Some rule names (e.g., email, date) may conflict with Laravel's built-in rules. Prefix custom rules (e.g., cake_email).
  3. Strict Typing

    • The validator expects strict data types. Cast input data explicitly if needed:
      $data = array_map('strval', $request->all()); // Ensure strings
      
  4. No Automatic Sanitization

    • Unlike Laravel's validator, this package does not sanitize input by default. Use filter_var() or similar for security.

Debugging Tips

  1. Enable Debug Mode Set debug to true in the validator for detailed error messages:

    $validator = new Validator(['debug' => true]);
    
  2. Inspect Rules Dump the validator's rules to debug:

    dd($validator->getRules());
    
  3. Test Edge Cases Validate with null, empty strings, and malformed data to catch rule issues early.

Extension Points

  1. Custom Validators Extend Cake\Validation\Validator to add domain-specific rules:

    class MyCustomValidator extends Validator {
        public function __construct() {
            $this->add('ssn', 'ssnFormat', [
                'rule' => function ($value) {
                    return preg_match('/^\d{3}-\d{2}-\d{4}$/', $value);
                }
            ]);
        }
    }
    
  2. Plugin Integration Use the package alongside Laravel's validator for hybrid validation:

    $cakeValidator = new Validator();
    $laravelValidator = Validator::make($data, [
        'email' => 'required|email',
    ]);
    
    $errors = $cakeValidator->validate($data);
    if ($errors) {
        $laravelValidator->errors()->merge($errors);
    }
    
  3. Performance Optimization Reuse validator instances for repeated validations (e.g., in loops):

    $validator = new Validator();
    foreach ($items as $item) {
        $validator->validate($item); // Reuse instance
    }
    
  4. Configuration Override default settings via constructor:

    $validator = new Validator([
        'allowEmpty' => false, // Disallow empty values
        'preserveData' => true // Keep original data on failure
    ]);
    
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.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views