In my view I have looped input select and passed array to the controller so that I can attach it to my pivot table:
VIEW
{!! Form::open(['url'=>'surveys/'.$survey_id.'/persons/'.$person_id]) !!}
@foreach($questions as $question)
<ol>{{ $question->description }}</ol>
<select name="answers[]">
<option value=""></option>
@foreach($answers as $answer)
@if($answer->question_id == $question->id)
<option value="{{ $answer->question_id }}">{{ $answer->answer }}</option>
@endif
@endforeach
</select>
@endforeach
{!! Form::submit('submit',['class'=>'btn btn-primary']) !!}
{!! Form::close() !!}
CONTROLLER
$input = Request::input('answers');
$person = Person::findOrFail($person_id);
$check_if_existing = $person->answers()->find($person_id);
if (empty($check_if_existing))
{
foreach($input as $answer)
{
$person->answers()->attach($answer);
}
}else{
$person->answers()->updateExistingPivot($person_id,$input);
}
I fetch the array using Request::input('answers');. The Attache function works good, but the updating sucks. Can you help me out.
All you need to do is that, just use
sync
instead ofattach
:No need to loop and
sync
accepts array ofid
s (including additional values). So, only one line of code is enough.