dimanche 28 février 2016

Laravel 5.1 Creating and Updating Dynamically Created Form Field Array

I have a survey which can have many questions - a belongs to many relationship. The fields for the questions are dynamically created as follows. The question_num is the array index value.

How can you create and update the questions table in this scenario. I tried the following but it doesnt work?

foreach ($request->input('questions') as $key => $val) {
   $survey->questions()->updateOrCreate(['survey_id' => $request->input('survey_id'), 'question_num' => $key], $request->input('questions'));
}

Form:

{{ Form::hidden('survey_id', '1') }}

{{ Form::text('questions[0][question_text]', null, array('class'=>'form-control')) }}
{{ Form::text('questions[0][question_answer]', null, array('class'=>'form-control')) }}


{{ Form::text('questions[1][question_text]', null, array('class'=>'form-control')) }}
{{ Form::text('questions[1][question_answer]', null, array('class'=>'form-control')) }}

Questions table

CREATE TABLE `questions` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`survey_id` INT(10) UNSIGNED NOT NULL,
`question_num` INT(10) UNSIGNED NOT NULL,
`question_text` VARCHAR(150) NOT NULL COLLATE 'utf8_unicode_ci',
`question_answer` TINYINT(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `question_num_survey_id_unique` (`question_num`, `survey_id`),
INDEX `survey_id_foreign` (`survey_id`)
CONSTRAINT `survey_id_foreign` FOREIGN KEY (`survey_id`) REFERENCES `surveys` (`id`)
)



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire