I have 7 input fields. However the user may only pick a maximum of 3 subjects. How would I be able to update these inputs into my table?
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');
My aim is to end up with something like this:
DB::table('mytable')->where('id', 6)
->update(['subject' => $firstchosensubject,
'subjecttwo' => $secondchosensubject,
'subjectthree' =>$thirdchosensubject]);
So far I have:
$subjects = [];
$inputs = Input::all();
array_walk($inputs, function ($v, $k) use (&$subjects) {
if(starts_with($k, 'subject')) {
$subjects[$k] = $v;
}
});
$index = count($subjects);
Shown above I have all inputs in this $subjects
variable. How do I extract these values for table input?
I would suggest validating the inputs on the front end rather than trying to do with php. Here is some JQuery that would get you on your way
var numSubjects = 0;
$(".inputs").each(function(i, obj) {
if($(this).val() != ""){
numSubjects++;
}
});
if(numSubjects > 3){
// let the user know
}else{
// submit the form
}
you can always check if the val is not empty
$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);
By now you have only 3 val stored at array
DB::table('mytable')->where('id', 6)
->update(['subject' => $subjects[0],
'subjecttwo' => $subjects[1],
'subjectthree' =>$subjects[2]]);
View:
<input name="subject[]" id="list" type="checkbox" value="1">
Controller:
$topic = Input::get('subject');
foreach ($topic as $key =>$value ) {
DB::table('mytable')->where('id', $id)
->update(['subject' => $topic[0],
'subjecttwo' => $topic[1]]);
}