Laravel 11/Livewire 3.5调用自定义验证规则报错怎么解决?
问题
在Laravel 11 / Livewire 3.5项目中,通过以下命令创建了自定义验证规则:
php artisan make:rule LocationIsValidRule
对应的规则类代码如下:
<?php namespace App\Rules; use App\Library\Services\Interfaces\GetGeoLocationInterface; use Closure; use Illuminate\Contracts\Validation\ValidationRule; class LocationIsValidRule implements ValidationRule { public function validate(string $attribute, mixed $value, Closure $fail): void { // 使用spatie包处理地理位置验证的逻辑 ... } }
在Livewire组件中调用该规则时:
class MyComponent extends Component { ... protected function rules() { return [ 'title' => [ 'required', ... ], 'location' => [ 'required', 'string', 'min:3', 'max:100', [new LocationIsValidRule()], ], ]; } }
执行$this->validate();时出现错误:
trim(): Argument #1 ($string) must be of type string, App\Rules\LocationIsValidRule given
同时疑问:php artisan make:rule命令是否适用于Livewire场景?Livewire中自定义验证规则需要什么格式?
解决方案
- 移除规则外层的数组包裹,直接将规则实例放入规则列表:
'location' => [ 'required', 'string', 'min:3', 'max:100', new LocationIsValidRule(), // 去掉[]包裹 ],
php artisan make:rule命令完全适用于Livewire场景,你创建的规则类实现ValidationRule接口的格式是正确的,无需修改规则类结构。
错误原因
Livewire会将规则数组中的每个元素按验证规则处理,当你把规则实例放在子数组中时,系统会误将其当作字符串类型的规则(如required)处理,调用trim()时因类型不匹配抛出错误。直接将规则实例放入规则列表,Laravel和Livewire会正确识别这是自定义验证规则,调用其validate方法完成验证。
内容的提问来源于stack exchange,提问作者mstdmstd
相关产品推荐
相关产品推荐

