This package introduces new events for sync(), attach(), detach() or updateExistingPivot() methods on BelongsToMany relation.
This package introduces new events for sync(), attach(), detach() or updateExistingPivot() methods on BelongsToMany relation.
This package introduces new eloquent events for sync(), attach(), detach() or updateExistingPivot() methods on BelongsToMany relation.
In Laravel events are not dispatched when BelongsToMany relation (pivot table) is updated with sync(), attach(), detach() or updateExistingPivot() methods, but this package will help with that.
| Laravel Version | Package Tag | Supported | Development Branch |
|---|---|---|---|
| >= 5.5.0 | 3.* | yes | master |
| belongsToMany(Role::class); |
}
static::pivotAttached(function ($model, $relationName, $pivotIds, $pivotIdsAttributes) {
echo 'pivotAttached';
echo get_class($model);
echo $relationName;
print_r($pivotIds);
print_r($pivotIdsAttributes);
});
static::pivotUpdated(function ($model, $relationName, $pivotIds, $pivotIdsAttributes) {
echo 'pivotUpdated';
echo get_class($model);
echo $relationName;
print_r($pivotIds);
print_r($pivotIdsAttributes);
});
static::pivotDetached(function ($model, $relationName, $pivotIds) {
echo 'pivotDetached';
echo get_class($model);
echo $relationName;
print_r($pivotIds);
});
```php
class Role extends Model
{
....For attach() or detach() one event is dispatched for both pivot ids.
Running this code
$user = User::first();
$user->roles()->attach(1);You will see this output
pivotAttached
App\Models\User
roles
[1]
[1 => []]Running this code
$user = User::first();
$user->roles()->attach([1]);You will see this output
pivotAttached
App\Models\User
roles
[1]
[1 => []]Running this code
$user = User::first();
$user->roles()->attach(Role::first());You will see this output
pivotAttached
App\Models\User
roles
[1]
[1 => []]Running this code
$user = User::first();
$user->roles()->attach(Role::get());You will see this output
pivotAttached
App\Models\User
roles
[1, 2]
[1 => [], 2 => []]Running this code
$user = User::first();
$user->roles()->attach([1, 2 => ['attribute' => 'test']], ['attribute2' => 'test2']);You will see this output
pivotAttached
App\Models\User
roles
[1, 2]
[1 => [], 2 => ['attribute' => 'test', 'attribute2' => 'test2']]For sync() method event is dispatched for each pivot row.
Running this code
$user = User::first();
$user->roles()->sync([1, 2]);You will see this output
pivotAttached
App\Models\User
roles
[1]
[1 => []]
pivotAttached
App\Models\User
roles
[2]
[2 => []]Running this code
$user = User::first();
$user->roles()->detach([1, 2]);You will see this output
pivotDetached
App\Models\User
roles
[1, 2]Running this code
$user = User::first();
$user->roles()->updateExistingPivot(1, ['attribute' => 'test']);You will see this output
pivotUpdated
App\Models\User
roles
[1]
[1 => ['attribute' => 'test']]MIT
Free Software, Hell Yeah!
No open issues yet, or sync has not completed.