Laravel model events to connect / disconnect
I have 3 tables, products, taxonomies and product_taxonomy, as you can tell the 3rd table is a pivot table. In the taxonomy table, I keep a field called num_products that keeps track of the number of products that this taxonomy owns. Now, how can I trigger a model event every time a product is attached or detached from a taxonomy? I want to update this num_products value in a model event.
source to share
Laravel models have events that you can hook up. You have the following options:
- creature
- established
- renewal
- updated
- preservation
- saved
- deletion
- cross out
- recovery
- recovers
You would program it like this:
User::creating(function($user)
{
if ( ! $user->isValid()) return false;
});
Docs: http://laravel.com/docs/4.2/eloquent#model-events
Or you can use model observers that are baked. You have the following options:
- creature
- renewal
- preservation
You have to write a method in your model:
class UserObserver {
public function saving($model)
{
//
}
public function saved($model)
{
//
}
}
Then you can register and register an observer:
User::observe(new UserObserver);
Docs: http://laravel.com/docs/4.2/eloquent#model-observers
Hope it helps.
source to share