I read about Eloquent events but didn't see any attach
, detach
or sync
events there.
How to implement these Eloquent events?
I read about Eloquent events but didn't see any attach
, detach
or sync
events there.
How to implement these Eloquent events?
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.
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.
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'];
}