How to trigger model events on pivot tables in Laravel

Suppose we have an app where we have a couple of tasks and users and we want to be able to assign users to tasks.

But what if at the same time we want to know who assigned each user to each task? We can easily achieve this by taking advantage of Laravel's model events - for pivot tables.

We would need 3 tables: one for tasks, one for users and one for the assigning users to tasks:
```php
Schema::create('tasks', function (Blueprint $table) {
    $table->id();
    $table->string("title");
    ...
    $table->timestamps();
});

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string("username");
    ...
    $table->timestamps();
});

Schema::create('task_user', function (Blueprint $table) {
    $table->id();
    $table->foreignId("assignee_id")->constrained("users");
    $table->foreignId("skill_id")->constrained();
    $table->foreignId("user_id")->constrained();
    $table->timestamps();
});
```

### 1. Create the corresponding TaskUser pivot model. 
```bash
 php artisan make:model TaskUser --pivot
```

### 2. Add your event handlers.
```php
class TaskUser extends Pivot
{
    protected static function booted()
    {
        static::creating(function ($pivot_model) {
            // your implementation here
        });
        ...
    }
}
```

### 3. Let Laravel know which model it should use for the pivot table.
*This is the key* - *without* this step the callback described above will *not* be *executed*!
```php
//in the User model
public function tasks()
{
    return $this->belongsToMany(Task::class)
      ->using(TaskUser::class);
}
```

Now, you can do:
```php
$user->tasks()->attach($tasks);
```
*That's it!* Your event callbacks or corresponding observer methods should now be executed.

Denisa Halmaghi
28 Feb 2022
« Back to post