Does the eloquent connection / disconnection / synchronization work anyway?

I have a laravel project, and I need to do some calculations right after I save the model and attach some data to it.

Is there any event that fires in laravel after calling attach (or disconnecting / syncing)?

+15
source share
3 answers

Steps to solve your problem:

  1. Create Custom Relationships BelongsToMany
  2. In BelongsToMany user relationships override attach, detach, sync, and updateExistingPivot methods
  3. In the redefined dispatch method of the desired events.
  4. Override the ownToMany () method in Model and return your user relationship, not the default one

what is it. I created a package that already does this: https://github.com/fico7489/laravel-pivot

+9
source

No, there are no related events in Oratory. But you can easily do it yourself (given, for example, the Ticket belongsToMany Component relation):

 // Ticket model use App\Events\Relations\Attached; use App\Events\Relations\Detached; use App\Events\Relations\Syncing; // ... public function syncComponents($ids, $detaching = true) { static::$dispatcher->fire(new Syncing($this, $ids, $detaching)); $result = $this->components()->sync($ids, $detaching); if ($detached = $result['detached']) { static::$dispatcher->fire(new Detached($this, $detached)); } if ($attached = $result['attached']) { static::$dispatcher->fire(new Attached($this, $attached)); } } 

the event object is simple like this:

 <?php namespace App\Events\Relations; use Illuminate\Database\Eloquent\Model; class Attached { protected $parent; protected $related; public function __construct(Model $parent, array $related) { $this->parent = $parent; $this->related = $related; } public function getParent() { return $this->parent; } public function getRelated() { return $this->related; } } 

then the main listener as a reasonable example:

  // eg. AppServiceProvider::boot() $this->app['events']->listen('App\Events\Relations\Detached', function ($event) { echo PHP_EOL.'detached: '.join(',',$event->getRelated()); }); $this->app['events']->listen('App\Events\Relations\Attached', function ($event) { echo PHP_EOL.'attached: '.join(',',$event->getRelated()); }); 

and use:

 $ php artisan tinker >>> $t = Ticket::find(1); => <App\Models\Ticket> >>> $t->syncComponents([1,3]); detached: 4 attached: 1,3 => null 

Of course, you can do this without creating Event objects, but this method is more convenient, flexible, and simply better.

+25
source

Laravel 5.8 now fires events -> attach ()

Check: https://laravel.com/docs/5.8/releases

And search: Pivot Intermediate Table / Events

https://laracasts.com/discuss/channels/eloquent/eloquent-attach-which-event-is-fired?page=1

0
source

Source: https://habr.com/ru/post/983497/


All Articles