You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel软删除数据恢复失败报404错误,疑路由问题求排查

Laravel软删除恢复时404错误的解决办法

问题核心

你的恢复接口返回404,本质是Laravel路由模型绑定默认只查询未被软删除的数据。当点击恢复按钮请求已删除的Course模型时,框架找不到对应记录,直接返回404。

修复方案

方案一:修改路由,允许绑定软删除模型

在恢复路由后添加->withTrashed()(允许绑定所有数据,包括已删除)或->onlyTrashed()(仅允许绑定已删除数据):

// 仅允许恢复已删除的Course
Route::get('/dashboard/courses/restore/{course}', [DashboardCourseController::class, 'restore'])->onlyTrashed();

此时控制器方法可以简化,因为路由已经帮你拿到了已删除的模型:

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

方案二:放弃路由模型绑定,直接用ID查询

如果不想修改路由规则,可以直接接收ID参数,手动查询已删除数据:

// 路由保持不变
Route::get('/dashboard/courses/restore/{course}', [DashboardCourseController::class, 'restore']);

修改控制器方法:

public function restore($courseId)
{
    // 仅查询已删除的数据,找不到则抛出404
    $course = Course::onlyTrashed()->findOrFail($courseId);
    $course->restore();
    return redirect('/dashboard/courses/recycle')->with('success', 'Course has been restored');
}

额外检查项

  1. 确认Course模型已引入SoftDeletes trait:
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Course extends Model
{
    use SoftDeletes;

    // ...其他模型配置
}
  1. 确认数据库的courses表存在deleted_at字段(可通过迁移添加:$table->softDeletes();)

内容的提问来源于stack exchange,提问作者Fauzan Zaman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 16:55:21