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 Pivot Laravel Package

fico7489/laravel-pivot

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require fico7489/laravel-pivot
    
    • Automatically resolves the correct version for your Laravel instance (5.5+).
  2. Enable Events Use the PivotEventTrait in your base model (recommended) or specific models:

    use Fico7489\Laravel\Pivot\Traits\PivotEventTrait;
    use Illuminate\Database\Eloquent\Model;
    
    abstract class BaseModel extends Model
    {
        use PivotEventTrait;
    }
    
    • No additional configuration required.
  3. First Use Case Listen for pivot events in a ModelObserver or service provider:

    // app/Observers/UserObserver.php
    public function pivotAttached($model, $relation, $pivot)
    {
        Log::info("User {$model->id} attached to {$relation} via pivot {$pivot->id}");
    }
    
    • Register the observer in AppServiceProvider@boot():
      User::observe(UserObserver::class);
      

Implementation Patterns

Core Workflows

  1. Syncing Relationships with Events

    $user->roles()->sync([1, 2, 3]); // Triggers pivotAttaching/pivotAttached
    
    • Event Order: pivotAttachingsync logic → pivotAttached (for new attachments). pivotDetachingsync logic → pivotDetached (for removals).
  2. Detaching with Granular Control

    $user->roles()->detach(3); // Triggers pivotDetaching/pivotDetached
    
    • Useful for audit logs or real-time notifications (e.g., Slack alerts).
  3. Updating Pivot Data

    $user->roles()->updateExistingPivot(1, ['expires_at' => now()]);
    // Triggers pivotUpdating/pivotUpdated
    
    • Ideal for workflows like role expiration or custom metadata updates.
  4. Dynamic Event Handling

    // Listen to all pivot events dynamically
    $model->pivotEvents()->each(function ($event) {
        Log::channel('pivot')->info($event);
    });
    

Integration Tips

  • Service Providers: Centralize event listeners for pivot operations:
    // app/Providers/EventServiceProvider.php
    protected $listen = [
        'pivotAttached' => [
            'App\Listeners\LogPivotAttachment',
        ],
    ];
    
  • API Responses: Modify responses post-pivot events:
    public function pivotAttached($model, $relation, $pivot)
    {
        cache()->forget("user_{$model->id}_$relation");
    }
    
  • Testing: Mock pivot events in unit tests:
    $this->expectsEvents(PivotAttached::class)
         ->when($user->roles()->attach(1));
    

Gotchas and Tips

Pitfalls

  1. Trait Placement

    • Issue: Forgetting to include PivotEventTrait in models breaks event dispatching.
    • Fix: Extend a base model or use a trait in every relevant model.
  2. Event Order Confusion

    • Issue: Assuming pivotAttached fires after sync() completes (it does, but pivotAttaching fires before).
    • Fix: Use pivotAttaching for pre-validation logic (e.g., permissions).
  3. Laravel 5.5+ Only

    • Issue: Attempting to use the package on Laravel <5.5 throws errors.
    • Fix: Use the laravel-5.4 branch if necessary (check releases).
  4. Custom Pivot Tables

    • Issue: Events may not fire if the pivot table is custom-named (e.g., user_role instead of role_user).
    • Fix: Ensure the belongsToMany definition matches the actual pivot table name.

Debugging

  • Event Not Firing?

    • Verify the trait is loaded (check composer dump-autoload).
    • Use dd($model->pivotEvents()) to inspect available events.
    • Check for typos in event names (e.g., pivotAttached vs. pivot_attached).
  • Performance Impact

    • Tip: Disable events in bulk operations:
      $model->pivotEvents(false);
      $model->roles()->sync([...]); // No events
      $model->pivotEvents(true);   // Re-enable
      

Extension Points

  1. Custom Events Extend the trait to add domain-specific events:

    // app/Traits/CustomPivotEvents.php
    public static function bootCustomPivotEvents()
    {
        static::addPivotEvent('pivotApproving', 'pivotApproved');
    }
    
  2. Pivot Data Validation Hook into pivotUpdating to validate pivot attributes:

    public function pivotUpdating($model, $relation, $pivot, $attributes)
    {
        if ($attributes['expires_at'] < now()) {
            throw new \Exception('Invalid expiration date');
        }
    }
    
  3. Real-Time Updates Pair with Laravel Echo/Pusher for live notifications:

    public function pivotAttached($model, $relation, $pivot)
    {
        broadcast(new PivotAttached($model, $relation, $pivot));
    }
    
  4. Database Transactions Wrap pivot operations in transactions to ensure data consistency:

    DB::transaction(function () use ($user) {
        $user->roles()->sync([1, 2]);
    });
    
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
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