Laravel验证报错:Validator::validateExists.types不存在的解决方法
解决Laravel ItemRequest验证错误:
validateExists.types不存在 问题根源
你的验证规则中exists.types的语法不符合Laravel的exists验证规则规范,Laravel要求exists规则使用**冒号(:)**分隔表名和字段名,而非点号(.);同时存在一处拼写错误。
修正后的代码
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; class ItemRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return Auth::check(); } /** * Get the validation rules that apply to the request. * * @return array<string, mixed> */ // validasi data public function rules() { return [ 'nama' => 'required|string|max:255', // 修正exists规则语法:将.改为:,明确指定验证字段为id 'type_id' => 'required|integer|exists:types,id', 'brand_id' => 'required|integer|exists:brands,id', 'photos' => 'nullable|array', // 修正拼写错误:nulable改为nullable 'photos.*' => 'nullable|image|mimes:jpeg,png,jpg|max:2048', 'features' => 'nullable|string', 'price' => 'required|numeric', 'star' => 'nullable|numeric', 'review' => 'nullable|numeric' ]; } }
额外说明(更新场景适配)
如果是在更新数据时,需要排除当前记录本身(避免验证自身ID冲突),可以修改exists规则为:
'type_id' => 'required|integer|exists:types,id,' . $this->route('item')->id, 'brand_id' => 'required|integer|exists:brands,id,' . $this->route('item')->id,
注:$this->route('item')中的item需对应你路由中定义的参数名称。
内容的提问来源于stack exchange,提问作者saf_
相关产品推荐
相关产品推荐

