環境:
laravel@8.83.23
事象:
Model を soft-delete し、その後 restore 時に特定の処理をしたいが処理が実行されない。
cannot works:
@models/User.php
protected static fucntion boot() {
parent::boot();
static::deleted(function ($user) {
$user->profileDetail()->delete(); // works fine
})
static::updated(function ($user) {
$user->name = "updated";
$user->save(); // works fine
})
static::restored(function ($user) {
$user->profileDetail()->restore(); // cannot works ????
})
}
原因:
User を restore するときに 一意の model を指定していなかったため
User::where('id', $request->id)->withTrashed()->restore(); // requested user will be restore but cannot trigger static::restored(function ($user))
solution)
User::where('id', $request->id)->withTrashed()->first()->restore();