Search code examples
laravellaravel-8soft-delete

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>

Solution

  • 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');
    }