Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cooperino's avatar

update or create and restore soft deleted model

If I want to updateOrCreate a soft deleted model, do I have to manually restore it as I do now:

MyModel::restore();
MyModel::updateOrCreate([
    // .. data
]);

Because this way it always makes an extra query (restore), even though it's not always necessary. If it should only be created then it's redundant but it's still done. Although it's very convenient. But perhaps there's a way to both update and restore the soft deleted model only when needed?

I can do a different thing of first checking if it exists and is deleted and then update or create but that's another extra query?

Update: I think I just needed to add withTrashed and it should work:

MyModel::withTrashed()->updateOrCreate([
    // .. data
]);

The problem was that the updateOrCreate did not know about the soft deleted model in the first place

0 likes
2 replies
MohamedTammam's avatar
Level 51

Great you find the answer, I just want to add, If you want to restore the model also with updateOrCreat you can set the deleted_at to null

MyModel::withTrashed()->updateOrCreate([
   'foo' => $foo,
	// ...
], [
   'deleted_at' => null,
	// ...
]);
2 likes

Please or to participate in this conversation.