Request data
{
"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,
}
],
}
Where student_id and subject_id is a unique composite key, how to make validator for composite key with Rule Method that accepts array of data () I tried but it does not work as expected.
$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'))
})
],
]);
below request should not validate data. but it validates successfully.
{
"exam_id": 10,
"exam_scores": [
{
"student_id": 1,
"subject_id": 1,
"marks": 50,
},
{
"student_id": 1,
"subject_id": 1,
"marks": 70,
}
],
}
Below request successfully validate data with single object of exam_scores that is expected.
{
"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'))
})
],
]);
After searching lots of Blogs, Tutorials & of course laravel Documentation, I got something that is solved my problem here is the blog link. that was not what I exactly wanted but it clears concept of what I have to do. this guy saves my day.
Validate Dynamic request Values
Here is an example.
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;
}
}
The solution were pretty much simple and easy.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.