Update model props in "deleting" event not working as expected #54168
Unanswered
ryanmortier
asked this question in
Ideas
Replies: 1 comment 2 replies
-
To make this work, I believe it would require the Not sure if that would be accepted, happy to take a stab at it if this gets marked as "Help Wanted." In the interim, you could make your own SoftDeletes trait that override just that single function trait SoftDeletesTrait
{
use SoftDeletes;
protected function runSoftDelete()
{
$query = $this->setKeysForSaveQuery($this->newModelQuery());
$time = $this->freshTimestamp();
/**
* I haven't tested this, but here we are merging the dirty columns + the deleted_at column
*/
$columns = $this->getDirty() + [$this->getDeletedAtColumn() => $this->fromDateTime($time)];
$this->{$this->getDeletedAtColumn()} = $time;
if ($this->usesTimestamps() && ! is_null($this->getUpdatedAtColumn())) {
$this->{$this->getUpdatedAtColumn()} = $time;
$columns[$this->getUpdatedAtColumn()] = $this->fromDateTime($time);
}
$query->update($columns);
$this->syncOriginalAttributes(array_keys($columns));
$this->fireModelEvent('trashed', false);
}
} |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Laravel Version
11.37.0
PHP Version
8.3.15
Database Driver & Version
No response
Description
Similar to #31754
I am using the
deleting
event like so:Unfortunately, the status is not being updated when the model is persisted. I've verified the event is being hit by dumping/logging the model inside the method.
In any of the other events ending with
ing
(creating, updating, restoring), I can update a property on the model before it's persisted. For example, I'm doing this with therestoring
event and it's working:It's only the
deleting
event that this doesn't work. I'm trying to avoid doing a second database query to update the status when the model is soft-deleted.The second query isn't that big of a deal unless you have a bulk delete feature and then you have n*2 queries. For example:
The
restoring
event does one query:While the
deleting
event, I'm forced to put a$workOrder->save()
at the end of the event method to persist the change which causes two queries:Steps To Reproduce
Beta Was this translation helpful? Give feedback.
All reactions