0

I have code that is using the withTrashed() and restore() methods. Its working but it is restoring everything, not just the ID I want restored. Not sure how to fix that.

Restore function

public function Restore($id){

    $delete = Category::find($id)->withTrashed()->restore();
    return redirect()->back()->with('success','Category has been restored successfully!');
}

Link and route for restore

<a href="{{ url('category/restore/'.$category->id) }}" class="btn btn-info btn-sm">Restore</a>
Route::get('/category/restore/{id}', [CategoryController::class, 'Restore']);

Model

   public function user()
    {
        return $this->hasOne(User::class,'id','user_id');
    }
Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
ToddM
  • 79
  • 1
  • 8
  • 1
    You have the code in the wrong order... `Category::find($id)->withTrashed()->restore()` should be `Category::withTrashed()->find($id)->restore()`. – Tim Lewis May 20 '21 at 14:25
  • It doesn't restore anything like that – ToddM May 20 '21 at 14:28
  • This works for me `Category::onlyTrashed()->findOrFail($id)->restore();` – STA May 20 '21 at 14:28
  • It wont restore if `$id` doesn't exist, probably `find($id)` returns null, you can use `findOrFail($id)`, it will raise a 404 error if $id doesn't exist on table – STA May 20 '21 at 14:29
  • 1
    Either way, your code needs to be in the correct order. For example, if you did `Model::find($id)`, it'll return an instance of `Model`. If you then call a query function (like `withTrashed()`), **it'll start a new query without the `... WHERE id = ?` clause**. If you then chain a closure (like `restore()`), the query being run is `UPDATE model SET deleted_at = NULL`. Order of operations is important due to how models work. If you want an example, run `Category::find($id)->query()->delete()` and watch all of your records get deleted instead of just the one (Don't actually run that) – Tim Lewis May 20 '21 at 14:33
  • si I looked at Restore and it is passing the same ID for all entries. Any ideas? – ToddM May 20 '21 at 14:38
  • I figured it out. I was passing the wrong variable Restore should be Restore – ToddM May 20 '21 at 15:30

0 Answers0