Laravel表单验证报错:Call to undefined method Query\Builder::withTrashed()
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

