2017 © Pedro Peláez
 

library belongstomanywithevents

Override of Laravel Eloquent BelongsToMany relationship to fire events on attach/detach operations

image

nylontechnology/belongstomanywithevents

Override of Laravel Eloquent BelongsToMany relationship to fire events on attach/detach operations

  • Sunday, June 10, 2018
  • by stpangia
  • Repository
  • 2 Watchers
  • 0 Stars
  • 2 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 1 Versions
  • 0 % Grown

The README.md

BelongsToManyWithEvents

Override of Laravel Eloquent BelongsToMany relationship to fire events on attach/detach operations, (*1)

Install

$ composer require nylontechnology/belongstomanywithevents

Usage

  1. Import into your model
use NylonTechnology\BelongsToManyWithEvents as BelongsToMany;

class User extends Model {
....
  1. 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');
    }

    ...
  1. 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) {}

        ...
  1. 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)

The Versions

10/06 2018

dev-master

9999999-dev

Override of Laravel Eloquent BelongsToMany relationship to fire events on attach/detach operations

  Sources   Download

MIT

The Requires