nylontechnology / belongstomanywithevents
Override of Laravel Eloquent BelongsToMany relationship to fire events on attach/detach operations
dev-master
2021-03-25 18:39 UTC
This package is not auto-updated.
Last update: 2024-09-26 00:24:45 UTC
README
Override of Laravel Eloquent BelongsToMany relationship to fire events on attach/detach operations
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.
Inspired by @andyberry88's gist