Back

Triggering model event when modifying relationship


I am trying to set up my models such that a few of them can get stored in a cache. What I'm trying to do is set it up such that whenever one of these models, or any of its children are created/modified, that root model's events are triggered and the cache for that model is rebuilt.

However, I can't seem to get things like attach() and sync() to fire the updated or saved events.

For example, if I do this:

Game::create(Input::all())->sections()->attach(Input::get('section'));

The expected behavior is that the attach() call should trigger the updated event in either the Game model, or Section models (whatever sections() ends up operating on), such that I can then do something like this:

   public static function boot()
{
	parent::boot();
	
	static::updated(function($Game) {
		$Game->sections->each(function($Section) {
			$Section->cache();
		});
	});
}

Or

   public static function boot()
{
	parent::boot();
	
	static::updated(function($Section) {
		$Section->cache();
	});
}

But there are seemingly two problems:

  1. The updated event is NOT being triggered
  2. Even if it was, calling attach() doesn't actually update the model in memory (or return it) with its new attachments. I won't have access to the sections unless I deliberately re-query the newly created Game.

I'm at a bit of a loss. Is there an easy way to listen to for ANY changes to an object dependency graph so as to be able to reliably cache the most recent version? I would rather not have to call $parent->cache() in every situation where one of its children (or children's children) gets created or updated.

tomvo replied 3 years ago

I'm looking for the same thing. You found an answer?

trideout replied 3 years ago

Currently looking for a solution here. Any success?

acacha replied 1 year ago

Touching timestamps could help you?

http://laravel.com/docs/5.1/eloquent-relationships#touching-parent-timestamps

fico7489 replied 4 days ago

check this package : https://github.com/fico7489/laravel-updated-related


Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us