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 Model Validation Rules Laravel Package

korridor/laravel-model-validation-rules

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Add the package via Composer:

    composer require korridor/laravel-model-validation-rules
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Korridor\LaravelModelValidationRules\ServiceProvider"
    
  2. Basic Usage Validate if a model exists by its ID or attribute:

    use Korridor\LaravelModelValidationRules\Rules\Exists;
    
    $validator = Validator::make($request->all(), [
        'user_id' => ['required', new Exists(User::class)],
    ]);
    
  3. First Use Case Validate a belongsTo relationship in a form submission:

    $validator = Validator::make($request->all(), [
        'author_id' => ['required', new Exists(Author::class)],
    ]);
    

Implementation Patterns

Common Workflows

  1. Validation in Form Requests Extend FormRequest and use the rule:

    public function rules()
    {
        return [
            'category_id' => ['required', new Exists(Category::class)],
        ];
    }
    
  2. Dynamic Model Validation Pass a dynamic model class (e.g., from a config or API):

    $modelClass = config('app.active_model');
    $validator->addRules([
        'reference_id' => [new Exists($modelClass)],
    ]);
    
  3. Customizing Validation Logic Override default behavior (e.g., check for soft-deleted models):

    $rule = new Exists(User::class, true); // Allow soft-deleted records
    
  4. API Resource Validation Validate nested resources in API payloads:

    $validator = Validator::make($request->all(), [
        'post.category_id' => [new Exists(Category::class)],
    ]);
    
  5. Integration with Laravel Policies Combine with policies for authorization:

    $rule = new Exists(User::class, false, function ($identifier, $model) {
        return $model->can('edit', auth()->user());
    });
    

Gotchas and Tips

Pitfalls

  1. Performance with Large Datasets

    • The rule queries the database per validation. For bulk operations, cache results or use exists in a query scope:
      $validator->after(function ($validator) {
          if ($validator->errors()->has('user_id')) {
              $validator->errors()->add('user_id', 'Invalid user ID.');
          }
      });
      
  2. Soft Deletes by Default

    • The rule excludes soft-deleted models by default. Pass true to allow them:
      new Exists(User::class, true) // Allows soft-deleted records
      
  3. Case Sensitivity in Attributes

    • Ensure attribute names match the model’s fillable fields exactly (e.g., user_id vs UserId).
  4. Custom Primary Keys

    • The rule assumes id as the primary key. Specify a custom key:
      new Exists(User::class, false, null, 'uuid')
      

Debugging Tips

  • Log Failed Validations Add a custom message for debugging:

    new Exists(User::class, false, null, null, 'User with ID {0} does not exist.')
    
  • Check Model Events If validation fails unexpectedly, verify retrieved or retrieving model events aren’t interfering.

Extension Points

  1. Custom Validation Logic Pass a closure to validate additional conditions:

    new Exists(User::class, false, function ($id, $user) {
        return $user->isActive();
    })
    
  2. Extend the Rule Create a custom rule class:

    class ActiveExists implements Rule {
        public function passes($attribute, $value) {
            return (new Exists(User::class, false, function ($id, $user) {
                return $user->isActive();
            }))->passes($attribute, $value);
        }
    }
    
  3. Laravel 10+ Compatibility Ensure your Laravel version supports the package’s validation syntax. Test with:

    use Illuminate\Validation\Rule as ValidationRule;
    // Fallback to native rules if needed
    
  4. Testing Mock the rule in tests:

    $this->partialMock(Exists::class, 'passes')
         ->shouldReturn(false);
    
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.
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
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium