2

I read about Eloquent events but didn't see any attach, detach or sync events there.

How to implement these Eloquent events?

baikho
  • 5,203
  • 4
  • 40
  • 47
Hata Bomba
  • 183
  • 15
  • 1
    Possible duplicate of [Eloquent attach/detach/sync fires any event?](http://stackoverflow.com/questions/28925292/eloquent-attach-detach-sync-fires-any-event) – baikho Sep 12 '16 at 08:15
  • https://github.com/fico7489/laravel-pivot – fico7489 Dec 06 '17 at 15:44

3 Answers3

1

Update:

From Laravel 5.8 Pivot Model Events are dispatched like normal model.

https://laravel.com/docs/5.8/releases#laravel-5.8

You just need to add using(PivotModel::class) to your relation and events will work on the PivotModel.

    class User extends Model 
    {
        public function roles()
        {
            return $this->hasMany(App\Role::class)->using(UserRolePivot::class);
        }
    }

And Pivot Model

use Illuminate\Database\Eloquent\Relations\MorphPivot;

class UserRolePivot extends Pivot
{
      protected $dispatchesEvents = [
    'created' => RoleAttached::class,
    'deleted' => RoleDeleted::class,
];
}

Attach($id) will dispatch Created and Creating

Detach($id) will dispatch Deleting and Deleted,

Sync($ids) will dispatch the needed events too [Created,Creating,Deleting,Deleted]

Only dispatch() with out id doesn't dispatch any event until now.

Amr Ezzat
  • 341
  • 3
  • 12
0

Taylor refuses to add this to laravel core, even many people need these events, see laravel PR about that https://github.com/laravel/framework/pull/14988

But here is a package which soles the problem : https://github.com/fico7489/laravel-pivot

A package is well tested and well documented so many people started to use it.

fico7489
  • 7,931
  • 7
  • 55
  • 89
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/18173840) – forgivenson Dec 06 '17 at 17:10
  • ok, I updated my answer. My answer is a solution to the problem, many people have the same problem and I just want to help them... – fico7489 Dec 06 '17 at 17:28
-2

When attaching/detaching/syncing you are creating objects of related models. For example:

class User extends Model 
{
...
    public function roles()
    {
        return $this->hasMany(App\Role::class)
    }
...
}

Calling:

$user->roles()->attach(1);

creates a record in a pivot table.

Make UserRole model with user_id and role_id and use its eloquent events.

class UserRole extends Model
{
    protected $fillable = ['user_id', 'role_id'];
}