我有7个输入字段。但是,用户最多只能选择3个科目。我怎样才能将这些输入更新到我的表中?
public function searchgrouppost(){
$subject1 = Input::get('subject1');
$subject2 = Input::get('subject2');
$subject3 = Input::get('subject3');
$subject4 = Input::get('subject4');
$subject5 = Input::get('subject5');
$subject6 = Input::get('subject6');
$subject7 = Input::get('subject7');
我的目标是结束这样的事情:
DB::table('mytable')->where('id', 6)
->update(['subject' => $firstchosensubject,
'subjecttwo' => $secondchosensubject,
'subjectthree' =>$thirdchosensubject]);
到目前为止,我有:
$subjects = [];
$inputs = Input::all();
array_walk($inputs, function ($v, $k) use (&$subjects) {
if(starts_with($k, 'subject')) {
$subjects[$k] = $v;
}
});
$index = count($subjects);
如上所示,我在此$subjects
变量中有所有输入。如何为表输入提取这些值?
答案 0 :(得分:0)
你总是可以检查val是否为空
$subjects = [];
$inputs = Input::all();
array_walk($inputs, function ($v, $k) use (&$subjects) {
if(!empty($v) && starts_with($k, 'subject')) {
$subjects[$k] = $v;
}
});
$index = count($subjects);
到目前为止,你只有3个val存储在数组
DB::table('mytable')->where('id', 6)
->update(['subject' => $subjects[0],
'subjecttwo' => $subjects[1],
'subjectthree' =>$subjects[2]]);
答案 1 :(得分:-1)
我建议验证前端的输入而不是尝试使用php。这是一些可以帮助你的JQuery
var numSubjects = 0;
$(".inputs").each(function(i, obj) {
if($(this).val() != ""){
numSubjects++;
}
});
if(numSubjects > 3){
// let the user know
}else{
// submit the form
}
答案 2 :(得分:-1)
查看:
<input name="subject[]" id="list" type="checkbox" value="1">
控制器:
$topic = Input::get('subject');
foreach ($topic as $key =>$value ) {
DB::table('mytable')->where('id', $id)
->update(['subject' => $topic[0],
'subjecttwo' => $topic[1]]);
}