此代码有什么问题?
class DeleteDetail extends FormRequest {
public function authorize() {
return true;
}
public function rules() {
$request = Request::all();
$rules = [
'hobby' => [
'string',
'between:3,20',
Rule::exists('user_hobby')->where(function ($query) use ($request) {
$query->where('hobby', $request['hobby'])->where('user_id', Auth::user()->id);
}),
],
];
return Validator::make($request, $rules);
}
}
我遇到的错误:
传递给Illuminate \ Validation \ Factory :: make()的参数2必须为数组类型,给定对象
答案 0 :(得分:3)
您从rules
方法本身内部返回了错误的值,应该返回array containing your validation rules
而不是Validation::make
:
public function rules() {
...
return $rules;
}
答案 1 :(得分:1)
您的rules
函数应返回带有规则的数组。
public function rules() {
$request = Request::all();
$rules = [
'hobby' => [
'string',
'between:3,20',
Rule::exists('user_hobby')->where(function ($query) use ($request) {
$query->where('hobby', $request['hobby'])->where('user_id', Auth::user()->id);
}),
],
];
return $rules;
}
然后在您的控制器中:
public function store(DeleteDetail $request)
{
// the code in here has passed the validation..
}