Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the `pivot table` model to trigger the save/saved model events when attach or detach are called in Laravel?

In Laravel 4 how do I get the pivot table model to trigger the save/saved model events when attach or detach are called?

It seems that the pivot table 'TeamUser' below is not actually needed for the attach/detach methods to work, so at a guess I believe that the model representing the pivot table is never invoked. And so the events are never triggered.

To ask another way: When I call User::with('Team')->find(1)->teams()->attach(1); how to get TeamUser to trigger it's own events. Note that the above attach works perfectly fine, all the records are updated in the database.

User

class User extends Eloquent 
{
    // Relationship
    public function teams() 
    {
        return $this->belongsToMany('Team');
    }    
}

Team

class Team extends Eloquent 
{
    // Relationship
    public function users() 
    {
        return $this->belongsToMany('User');
    }    
}

Team User - The model for the TeamUser table/pivot table

class TeamUser extends Eloquent 
{
    public function save(array $options = array())
    {
        // do cool stuff when relationship is saved via
        // attach/detach
    }
}
like image 240
Chris Avatar asked Jan 17 '14 13:01

Chris


2 Answers

You can add a $touches to the Team model.

class Team extends Eloquent 
{
    protected $touches = array('TeamUser');

    // Relationship
    public function users() 
    {
        return $this->belongsToMany('User');
    }    
}

This will update the TeamUser updated_at field. I think this will also hit the save() method in the TeamUser model.

If that doesn't work, you can fire your own event in the Team save() method and listen to this event somewhere.

Event::fire('team.updated', array($team));
like image 145
JackPoint Avatar answered Oct 08 '22 01:10

JackPoint


With the new version of Laraval 5.8, Pivot tables trigger the boot events. Check the release notes: https://laravel.com/docs/5.8/releases#pivot

like image 39
Sonal Avatar answered Oct 08 '22 01:10

Sonal