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

Laravel表单验证报错:Call to undefined method Query\Builder::withTrashed()

Fixing "Call to undefined method Illuminate\Database\Query\Builder::withTrashed()" in Validation Rules

Hey there! Let's break down why this error is happening and how to fix it quickly.

The Root Cause

When you use Rule::unique('users') (passing the table name directly), Laravel uses the base Query Builder under the hood. This builder doesn't have the withTrashed() method—that's a method added exclusively to the Eloquent Builder by the SoftDeletes trait in your User model. Your closure is trying to call a method that doesn't exist on the Query Builder instance, hence the error.

The Solution

Instead of passing the table name to Rule::unique(), pass your User model class. This tells Laravel to use the Eloquent Builder (which inherits all the methods from your model's traits, including withTrashed()).

Here's your updated validation code:

request()->validate([
    'name' => [
        'required',
        Rule::unique(User::class, 'name')->where(function($query) {
            $query->withTrashed();
        })
    ],
    'email' => [
        'required',
        Rule::unique(User::class)->where(function($query) {
            $query->withTrashed();
        })
    ],
    'password' => 'required|min:6|max:20|confirmed',
    'g-recaptcha-response' => 'required|captcha',
]);

Why This Works

By using User::class as the first argument for Rule::unique(), Laravel initializes an Eloquent query builder tied directly to your User model. Since your model uses the SoftDeletes trait, the withTrashed() method is available on this builder, so your closure can call it without any issues.

If you really need to keep using the table name for some edge case, you can explicitly reference the model's query builder in the closure (though this is less clean):

Rule::unique('users', 'name')->where(function() {
    return User::query()->withTrashed();
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:49:54