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

RodrigoG's avatar

Restore soft deleted item and update fields

Hi !, I would like to know what would be the best way to handle this, I have been looking around the forum and I did not find something exact. I want to know how would be the most elegant way to handle when an element, with a UNIQUE field, is soft deleted and then I want to restore it, I have read here that it is best to update that element soft deleted updating the timestamp to null, the problem is how to do it At the same time it updates the data since for the user it is creating a new one with new data. I have done something like that but I don't know if there is a more elegant way to do it. Thank you all!

public function store(){
    
    $validatedData = $this->validate([
        'client_id' => 'required|integer|exists:clients,id',
        'code_job' => 'required|string|regex:/^\d{3}[\/]\d{3,4}$/|min:7|max:9|unique:jobs,code_job,NULL,id,deleted_at,NULL',
        'description' => 'required|max:60',
        'date_ini' => 'required|date_format:d-m-Y',
        'date_final' => 'nullable|date_format:d-m-Y|after_or_equal:date_ini',
        'close' => 'boolean|nullable',
        'location' => 'max:80|nullable',
        'observations' => 'max:255|nullable',
    ]);
    $this->job->withTrashed()->updateOrCreate(['code_job' => $this->code_job],$validatedData)->update(['deleted_at' => null]);
    session()->flash('success',__('¡Job success created!'));  
    return redirect()->route('admin.jobs.index');
}

Im using to render livewire component.

0 likes
3 replies
Snapey's avatar
Snapey
Best Answer
Level 122
$this->job->withTrashed()->updateOrCreate(
        ['code_job' => $this->code_job],
        $validatedData) + ['deleted_at' => null]);

RodrigoG's avatar

hi, Thanks for your answer! But the code gives me an error, I think there is a surplus of a parenthesis, can it be?

    $this->job->withTrashed()->updateOrCreate(
        ['code_job' => $this->code_job],
        $validatedData + ['deleted_at' => null]);

I found that this also works for me, I don't know which one will be better or more elegant to do it. This way I don't have to add deleted_at to fillable:

    $this->job->withTrashed()->updateOrCreate(['code_job' => $this->code_job],$validatedData)->restore();
Snapey's avatar

ok, but does two updates to the record.

1 like

Please or to participate in this conversation.