Laravel-错误“传递给Illuminate \ Validation \ Factory :: make()的参数2必须是数组类型,给定对象”

时间:2019-01-24 09:16:06

标签: laravel validation

此代码有什么问题?

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必须为数组类型,给定对象

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..
}