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 Relationship Events Laravel Package

chelout/laravel-relationship-events

Adds missing Eloquent relationship events to Laravel models. Use simple traits (HasOne/Many, BelongsTo/Many, Morph*) to listen for attach/detach/sync, saved/updated, and other relation lifecycle hooks with parent/related context and IDs/attributes.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Event-Driven Enhancement: The package extends Laravel’s Eloquent ORM by introducing relationship lifecycle events, filling a critical gap in native Laravel functionality. This aligns well with systems requiring audit trails, real-time notifications, or side-effect logic tied to relationship changes (e.g., syncing caches, triggering workflows).
  • Decoupled Design: Events are model-agnostic and can be consumed by observers, listeners, or dispatchable classes, promoting separation of concerns. This fits architectures leveraging event sourcing, CQRS, or reactive programming.
  • Polymorphic Support: Comprehensive coverage of all Laravel relationship types (1:1, 1:N, N:M, polymorphic) ensures broad applicability across domain models.

Integration Feasibility

  • Low Friction: Requires minimal boilerplate—just trait inclusion and event registration in boot(). No database migrations or schema changes are needed.
  • Laravel Native: Leverages Laravel’s service container, event system, and Eloquent hooks, reducing integration risk. Compatible with Laravel 6–13 and PHP 7.2–8.3.
  • Observer Compatibility: Supports Laravel observers, enabling centralized event handling (e.g., logging, analytics) without cluttering models.

Technical Risk

  • Performance Overhead:
    • Events trigger additional queries (e.g., fetching related collections for hasManyUpdated). Risk of N+1 queries if not optimized (e.g., eager loading).
    • Mitigation: Document query optimization strategies (e.g., with() clauses, caching).
  • Backward Compatibility:
    • Breaking changes possible in minor versions (e.g., event signature updates). SemVer adherence is critical; monitor v5.x for Laravel 13-specific changes.
    • Mitigation: Pin to a stable version (e.g., ^5.0) and test upgrades.
  • Testing Complexity:
    • Relationship events introduce indirect side effects (e.g., a hasManySaved event might trigger a queue job). Requires integration tests to verify event flows.
    • Mitigation: Provide test doubles for event handlers in unit tests.

Key Questions

  1. Use Case Alignment:
    • Are events primarily for auditing, real-time updates, or business logic? Prioritize accordingly (e.g., use observers for auditing, dispatchable events for workflows).
  2. Performance Budget:
    • Can the system tolerate additional queries during relationship operations? Profile with tntsearch/laravel-query-cache if needed.
  3. Event Granularity:
    • Does the team need fine-grained events (e.g., hasManyCreating vs. hasManySaved) or coarser-grained (e.g., aggregated RelationshipUpdated)?
  4. Observer vs. Listeners:
    • Will events be handled via observers (centralized) or model listeners (decentralized)? Observers reduce duplication but may complicate testing.
  5. Dispatchable Events:
    • Is the event class system (e.g., HasOneSaved::class) necessary, or are closures sufficient? Dispatchable events add complexity but enable queueing/retry logic.

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Native Integration: Works seamlessly with Laravel’s Eloquent, Events, and Observers. No external dependencies beyond Laravel core.
    • Queue/Jobs: Dispatchable events can integrate with Laravel Queues for async processing (e.g., sending emails on hasManySaved).
    • Testing: Compatible with Pest/PHPUnit and Mockery for event testing.
  • PHP Extensions:
    • Requires PDO (for Eloquent) and BCMath (for Laravel 13’s cryptographic improvements). No additional extensions needed.
  • Alternatives Considered:
    • Native Eloquent Hooks: Limited to creating, created, etc.—no relationship-specific events.
    • Custom Observers: More verbose; this package provides standardized event names.

Migration Path

  1. Assessment Phase:
    • Audit critical relationship operations (e.g., save(), attach(), associate()) to identify where events add value.
    • Example: If Post::tags()->sync() triggers side effects (e.g., updating a search index), this package eliminates manual hooks.
  2. Pilot Implementation:
    • Start with one model relationship (e.g., User::posts()) and implement HasManyEvents.
    • Test with observers first (simpler than dispatchable events).
  3. Phased Rollout:
    • Phase 1: Add events to high-impact relationships (e.g., order items, user roles).
    • Phase 2: Replace custom relationship logic (e.g., afterSave hooks) with package events.
    • Phase 3: Adopt dispatchable events for async workflows (e.g., sending notifications).

Compatibility

  • Laravel Versions:
    • v5.x targets Laravel 13 (PHP 8.3). Use v4.x for Laravel 12 if needed.
    • Downgrade Risk: Test with Laravel 10–12 if using older branches.
  • Third-Party Packages:
    • Potential Conflicts: Packages overriding Eloquent’s save() or create() (e.g., spatie/laravel-activitylog) may interfere.
    • Mitigation: Check for event listener priority or wrap package events in a try-catch.
  • Database:
    • No schema changes required. Works with MySQL, PostgreSQL, SQLite, SQL Server.

Sequencing

  1. Prerequisites:
    • Laravel 9+ (for PHP 8+ features used in newer versions).
    • Composer 2.x (for modern dependency resolution).
  2. Installation Order:
    composer require chelout/laravel-relationship-events
    
    • Run php artisan vendor:publish if extending default config (none exists yet).
  3. Model Updates:
    • Add traits to parent models (e.g., use HasManyEvents on Post for tags()).
    • Register events in boot() after parent::boot().
  4. Testing:
    • Write integration tests for event flows (e.g., verify hasManySaved fires on save()).
    • Example:
      public function test_has_many_saved_event()
      {
          $post = Post::factory()->create();
          $tag = Tag::factory()->create();
      
          $post->tags()->save($tag);
      
          $this->assertLogged('Tags have been attached to post '.$post->title);
      }
      
  5. Deployment:
    • Zero Downtime: Safe to deploy incrementally (events are opt-in per model).

Operational Impact

Maintenance

  • Package Updates:
    • Low Maintenance: MIT license, active development (last release: 2026-05-28). Monitor GitHub issues for breaking changes.
    • Upgrade Strategy:
      • Test minor versions in staging (e.g., v5.0.0v5.1.0).
      • Major versions (e.g., v4.xv5.x) may require Laravel upgrades.
  • Event Management:
    • Debt Risk: Unsubscribed events (e.g., unused hasOneUpdated) add technical debt. Document event ownership (e.g., "Team A owns OrderItem::hasManySaved").
    • Mitigation: Use IDE warnings or static analysis (e.g., PHPStan) to flag unused event listeners.

Support

  • Debugging:
    • Event Flow Tracing: Use dd() or Log::debug() in event handlers to trace execution.
    • Common Issues:
      • Missing Events: Ensure traits are added to the correct model (parent, not child).
      • Query Failures: Events like hasManyUpdated fetch related collections—ensure foreign keys are set.
  • Community:
    • Limited Support: 525 stars but no open-source maintainer listed. Rely on GitHub issues or self-hosted forks if critical.

Scaling

  • Performance at Scale:
    • Event Throttling: High-frequency events (e.g., morphToManyAttached in a tagging system) may overload queues.
      • Solution: Use Laravel Horizon to monitor queue jobs and adjust concurrency.
    • Database Load: Events trigger queries (e.g., belongsToAssociated fetches parent). Optimize with:
      • Caching: Cache related models if events are read-heavy.
      • Batching: Process bulk operations (e.g., sync()) in database transactions.
  • Horizontal Scaling:
    • **Stat
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.
codifyo/ts-generator-bundle
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