I want to track (record) the changes made to each row of the database. This means saving a log of each action (insert, update, delete) made for each record of each table.
This problem is solved for models as they extend from BaseModel, and I use model events . However, I cannot find a way to write changes from pivot tables.
Given the following tables users, profilesand profile_user(profile_id, user_id), I have the following code:
class User extends BaseModel {
public function profiles() {
return $this->belongsToMany('Profile');
}
}
class Profile extends BaseModel {
public function users() {
return $this->belongsToMany('User');
}
}
abstract class BaseModel extends Model {
public static function boot() {
parent::boot();
static::created(function($model) {
return LogTracker::saveRowCreatedOrUpdated($model, true);
});
static::updated(function($model) {
return LogTracker::saveRowCreatedOrUpdated($model, false);
});
static::deleted(function($model) {
return LogTracker::saveRowDeleted($model);
});
}
}
This allows me to record changes from userand profile, but not from profile_user.
ProfileUser, Pivot (Illuminate\Database\Eloquent\Relations\Pivot), , .
, , . , user ( profile):
class User extends BaseModel {
public function newPivot(Eloquent $parent, array $attributes, $table, $exists) {
if ($parent instanceof Profile) {
return new ProfileUser($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
}
, ( ).
sync():
$user->profiles()->sync(explode(',', $values["profiles"]));
, ( , ).
?