Updating pivot table from array of select in Laravel 5

148 Views Asked by At

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.

1

There are 1 best solutions below

0
On

All you need to do is that, just use sync instead of attach:

Person::findOrFail($person_id)->answers()->sync(Request::input('answers'));

No need to loop and sync accepts array of ids (including additional values). So, only one line of code is enough.