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

Laravel路由资源调用withTrashed报错:方法不存在原因咨询

问题说明

我编写了如下路由:

Route::apiResource('article.comment', ArticleCommentController::class)->except('destroy', 'update');
Route::apiResource('article.comment', ArticleCommentController::class)->only('update')->withTrashed();

执行php artisan r:l查看路由时,出现如下错误:

BadMethodCallException 

Method Illuminate\Routing\PendingResourceRegistration::withTrashed does not exist.

at D:\dev\api_app\vendor\laravel\framework\src\Illuminate\Macroable\Traits\Macroable.php:113
    109▕      */
    110▕     public function __call($method, $parameters)
    111▕     {
    112▕         if (! static::hasMacro($method)) {
  ➜ 113▕             throw new BadMethodCallException(sprintf(
    114▕                 'Method %s::%s does not exist.', static::class, $method
    115▕             ));
    116▕         }
    117▕

  • Bad Method Call: Did you mean Illuminate\Routing\PendingResourceRegistration::withoutMiddleware() ?

  1   D:\dev\api_app\routes\api.php:88
      Illuminate\Routing\PendingResourceRegistration::__call("withTrashed", [])

  2   D:\dev\api_app\vendor\laravel\framework\src\Illuminate\Routing\Router.php:423
      Illuminate\Routing\RouteFileRegistrar::{closure}(Object(Illuminate\Routing\Router))

请问为何无法在路由资源上调用->withTrashed()方法?

问题原因及解决方案

原因

withTrashed()是Eloquent查询构建器的专属方法,作用是让查询包含软删除的模型记录,但它并不是路由资源注册对象(PendingResourceRegistration)支持的方法。路由资源注册的链式调用只能使用路由配置相关的方法,比如middleware()、name()等,不能直接调用模型层面的查询方法。

解决方案

有两种实用的处理方式:

  1. 在控制器方法中添加查询逻辑
    直接在ArticleCommentController的update方法里,对目标模型的查询语句加上withTrashed():

    public function update(Request $request, Article $article, Comment $comment)
    {
        // 加载包含软删除的评论记录
        $targetComment = $comment->withTrashed()->findOrFail($comment->id);
        // 执行你的更新逻辑
        $targetComment->update($request->validated());
        // 返回响应...
    }
    
  2. 全局绑定路由参数逻辑
    在app/Providers/RouteServiceProvider.php的boot方法中,自定义comment参数的绑定规则,让所有使用该参数的路由自动查询包含软删除的记录:

    public function boot()
    {
        parent::boot();
    
        Route::bind('comment', function ($value) {
            return \App\Models\Comment::withTrashed()->findOrFail($value);
        });
    }
    

    这样设置后,所有涉及comment参数的路由都会自动应用这个查询规则,无需在每个控制器方法中重复编写。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:25:35