BelongsToManyWithEvents
Override of Laravel Eloquent BelongsToMany relationship to fire events on attach/detach operations, (*1)
Install
$ composer require nylontechnology/belongstomanywithevents
Usage
- Import into your model
use NylonTechnology\BelongsToManyWithEvents as BelongsToMany;
class User extends Model {
....
- In your model, define what relationship events you want to observe
class User extends Model {
protected $observables = [
'attached.roles',
'detached.roles'
];
public function roles()
{
return $this->belongsToMany('App\Role');
}
...
- Create an observer and handle events however you wish
namespace App\Observers;
class ModelAuditObserver {
private function attached($observer_callback, $model, $ids) {}
private function detached($observer_callback, $model, $ids) {}
private function synced($observer_callback, $model, $ids) {}
...
- Register your observer in AppServiceProvider boot() method
class AppServiceProvider extends ServiceProvider {
public function boot() {
App\User::observe(ModelAuditObserver::class);
...
Notes
sync() is a wrapper around attach() and detach() so generally you should only observe sync events or attach/detach, but not both unless you don't mind redundant events., (*2)
Inspired by @andyberry88's gist, (*3)