请求数据
{
"exam_id": 10,
"exam_scores": [
{
"student_id": 1,
"subject_id": 1,
"marks": 50,
},
{
"student_id": 1,
"subject_id": 2,
"marks": 70,
},
{
"student_id": 1,
"subject_id": 3,
"marks": 80,
}
],
}
其中student_id和subject_id是唯一的组合键, 如何使用接受数据数组的Rule方法为复合键创建验证器() 我试过了,但是没有按预期工作。
$validator = Validator::make(request()->all(), [
"exam_id"=> "required|integer",
"exam_scores"=> "required|array",
'exam_scores.*.student_id' => [
Rule::unique('results')->where(function ($query) {
return $query
->whereStudent_idAndSubject_id(request()->get('exam_scores.*.student_id'),request()->get('exam_scores.*.subject_id'))
})
],
]);
以下请求不应验证数据。但验证成功。
{
"exam_id": 10,
"exam_scores": [
{
"student_id": 1,
"subject_id": 1,
"marks": 50,
},
{
"student_id": 1,
"subject_id": 1,
"marks": 70,
}
],
}
以下请求成功地通过了带有期望的exam_scores对象的数据来验证数据。
{
"exam_id": 10,
"exam_scores": {
"student_id": 1,
"subject_id": 1,
"marks": 50,
}
}
$validator = Validator::make(request()->all(), [
"exam_id"=> "required|integer",
"exam_scores"=> "required|array",
'exam_scores.student_id' => [
Rule::unique('results')->where(function ($query) {
return $query
->whereStudent_idAndSubject_id(request()->get('exam_scores.student_id'),request()->get('exam_scores.subject_id'))
})
],
]);
答案 0 :(得分:0)
在搜索了许多博客,教程和laravel文档之后,我发现了一些可以解决的问题,这里是博客链接。那不是我真正想要的,但它清除了我必须做的事情的概念。 这个家伙救了我的命。
Validate Dynamic request Values
这里是一个例子。
namespace App\Http\Requests;
use App\Http\Requests\Request;
class OrderRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$rules = [
'name' => 'required|max:255',
];
foreach ($this->request->get('items') as $key => $val) {
$rules['items.' . $key] = 'required|max:10';
}
return $rules;
}
public function messages()
{
$messages = [];
foreach ($this->request->get('items') as $key => $val) {
$messages['items.' . $key . '.max'] = 'The field labeled "Book Title ' . $key . '" must be less than :max characters.';
}
return $messages;
}
}
解决方案非常简单容易。