Fauzan Zaman
Fauzan Zaman

Reputation: 69

Can't restore soft delete data in laravel

I tried to do soft delete but can't restore the data, it says error 404, i think there is something wrong with the route but i don't know for sure

The following soft delete code works fine for me:

public function destroy(Course $course)
{
    Course::destroy($course->id);
    return redirect('/dashboard/courses')->with('success', 'Course has been deleted');
}

this is the route to show all deleted data:

Route::get('/dashboard/courses/recycle', [DashboardCourseController::class, 'recycle']);

this is a function to restore data:

public function restore(Course $course)
{
    Course::onlyTrashed()->find($course->id)->restore();
    return redirect('/dashboard/courses/recycle')->with('success', 'Course has been restored');
}

and this is routing to restore data:

Route::get('/dashboard/courses/restore/{course}', [DashboardCourseController::class, 'restore']);

and this button to restore data:

<a href="/dashboard/courses/restore/{{ $course->id }}" class="badge bg-success"><span data-feather="rotate-ccw"></span></a>

Upvotes: 1

Views: 149

Answers (2)

persi bridaine
persi bridaine

Reputation: 31

i have the same issue ,there's no model binding by default concerning Soft deletes model,so to allow model binding you have to add to your withtrashed so as in this example:

Route::get('restore/{modelId}',[Model::class,'restore'])->withtrashed();

Upvotes: 3

Erik Dohmen
Erik Dohmen

Reputation: 287

In the restore method, you have dependency injection. You ask for the course to be retrieved based on the url and id used in there. But you can't retrieve the course there as it is deleted.

A solution would probably be to refactor the method to:

public function restore($courseId)
{
    Course::onlyTrashed()->find($courseId)->restore();
    return redirect('/dashboard/courses/recycle')->with('success', 'Course has been restored');
}

Upvotes: 3

Related Questions