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 Exists Rule Laravel Package

mvanduijker/laravel-model-exists-rule

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Validation Layer Alignment: The package extends Laravel’s validation ecosystem, fitting seamlessly into the existing FormRequest/Validator architecture. It complements Laravel’s built-in Rule::exists() by enabling Eloquent-specific queries (e.g., whereHas, joins, custom scopes).
  • Separation of Concerns: Encapsulates model existence checks in a reusable rule, reducing duplication in validation logic across controllers/requests.
  • Extensibility: Supports custom query builders, making it adaptable to complex relationships (e.g., polymorphic associations, soft-deleted models).

Integration Feasibility

  • Low Coupling: Requires minimal changes to existing validation logic. Can be adopted incrementally (e.g., replace Rule::exists() for specific cases).
  • Eloquent Dependency: Tightly coupled to Laravel’s Eloquent ORM, which may limit use in non-Eloquent contexts (e.g., raw query-based applications).
  • Validation Pipeline: Integrates natively with Laravel’s validator, requiring no middleware or service container modifications.

Technical Risk

  • Query Performance: Complex queries (e.g., whereHas with nested joins) could introduce N+1 or inefficient subqueries if not optimized. Risk mitigated by leveraging Eloquent’s query caching or with().
  • Model Scoping: Assumes models use default query scopes. Custom global scopes (e.g., globalScope) may alter behavior unpredictably.
  • Soft Deletes: May require explicit handling for soft-deleted models (e.g., withTrashed()) if not already configured in the query.
  • Testing Overhead: Validation rules must be tested for edge cases (e.g., invalid IDs, non-existent relationships). Automated tests should cover these scenarios.

Key Questions

  1. Use Case Scope:
    • Will this replace all Rule::exists() calls, or only for complex queries?
    • Are there performance bottlenecks in current validation queries that this could exacerbate?
  2. Model Complexity:
    • How many models require existence validation, and what’s the average query complexity?
    • Are there polymorphic relationships or multi-table joins needed?
  3. Testing Strategy:
    • How will validation rules be tested (unit vs. feature tests)?
    • Are there existing tests for Rule::exists() that need updating?
  4. Maintenance:
    • Who will own updates if Laravel’s validation system evolves (e.g., new rule methods)?
    • Is the package’s MIT license acceptable for the project’s licensing model?

Integration Approach

Stack Fit

  • Laravel Ecosystem: Ideal for Laravel 8+ applications using Eloquent. Compatible with:
    • FormRequests (recommended).
    • Manual validator instances (e.g., Validator::make()).
    • API resources or DTO validation layers.
  • Non-Laravel: Not applicable; requires Laravel’s validator and Eloquent.
  • Alternatives: Could compare with custom validation logic or libraries like spatie/laravel-validation-rules for broader features.

Migration Path

  1. Phase 1: Pilot Models
    • Start with 1–2 high-impact models (e.g., User, Order) to validate integration and performance.
    • Replace simple Rule::exists() calls with ModelExists for complex cases.
  2. Phase 2: Full Adoption
    • Update all validation rules using Rule::exists() to leverage ModelExists where needed.
    • Refactor custom validation logic (e.g., Model::findOrFail() in controllers) into rules.
  3. Phase 3: Optimization
    • Profile query performance for ModelExists rules.
    • Add query caching (e.g., ->remember()) or preload relationships where applicable.

Compatibility

  • Laravel Version: Tested with Laravel 8+ (last release 2026-03-06). Verify compatibility with your version.
  • PHP Version: Requires PHP 8.0+ (check Laravel’s minimum version).
  • Database: Works with any Eloquent-supported database (MySQL, PostgreSQL, SQLite, etc.).
  • Custom Rules: If extending Laravel’s validation further, ensure no conflicts with other rule packages.

Sequencing

  1. Dependency Installation:
    composer require mvanduijker/laravel-model-exists-rule
    
  2. Publish Config (if any): Check for optional config files (none in this package).
  3. Update Validation Rules:
    • Replace:
      'user_id' => ['required', Rule::exists('users', 'id')]
      
    • With:
      'user_id' => ['required', new ModelExists(\App\Models\User::class, 'id')]
      
  4. Advanced Usage:
    • Add joins/scopes:
      new ModelExists(\App\Models\Order::class, 'id')
          ->where('status', 'completed')
          ->whereHas('user', fn($q) => $q->active())
      
  5. Testing:
    • Write unit tests for new rules (e.g., mock Eloquent queries).
    • Validate edge cases (e.g., invalid IDs, soft deletes).

Operational Impact

Maintenance

  • Rule Updates: Monitor package updates for breaking changes (e.g., Laravel version drops).
  • Custom Logic: If extending the rule (e.g., adding scopes), document and test thoroughly.
  • Deprecation: Laravel’s Rule::exists() may evolve; assess if migration is needed when major Laravel updates occur.

Support

  • Debugging: Validation errors may require inspecting Eloquent queries (use ->toSql() for debugging).
  • Documentation: Package lacks extensive docs; internal documentation may be needed for complex use cases.
  • Community: Low stars (22) suggest limited community support; rely on GitHub issues or Laravel forums.

Scaling

  • Performance:
    • Pros: Reduces redundant Model::find() calls in controllers.
    • Cons: Complex queries could impact validation speed under high load. Mitigate with:
      • Query caching (e.g., ->remember(60)).
      • Preloading relationships in the request lifecycle (e.g., with() in the model).
  • Database Load: Existence checks add minimal overhead compared to manual queries.

Failure Modes

Scenario Impact Mitigation
Invalid model class Validation fails silently Use class_exists() checks or try-catch.
Unoptimized queries Slow validation Profile and add query caching.
Soft-deleted models False negatives Explicitly include withTrashed().
Eloquent global scopes Unexpected query behavior Test with all active scopes.
Package abandonment No future updates Fork or replace if critical.

Ramp-Up

  • Developer Onboarding:
    • Time: 1–2 hours to understand basic usage; longer for advanced queries.
    • Training: Document common patterns (e.g., joins, whereHas).
  • Testing:
    • Add validation tests to CI pipeline.
    • Include negative test cases (e.g., invalid IDs, non-existent relationships).
  • Adoption Barriers:
    • Resistance: Developers may prefer Rule::exists() for simplicity. Highlight benefits (e.g., Eloquent features, DRY validation).
    • Complexity: Advanced usage requires Eloquent query knowledge. Provide examples for common cases (e.g., polymorphic checks).
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.
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
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle