Search code examples
htmllaravellaravel-5.3

how to recuperate the value of the chosen option in checkbox with laravel?


I try to save the value of the chosen option of ckeckbox in database. but I get always the value "on" saved in my database even I did not chose any option. this is the code of answercontroller .

 public function store(Request $request, Survey $survey) 
  {

    // remove the token
    $arr = $request->except('_token');
    foreach ($arr as $key => $value) {
      $newAnswer = new Answer();
      if (! is_array( $value )) {
        $newValue = $value['answer'];
      } else {
        $newValue = json_encode($value['answer']);
      }

      $newAnswer->answer = $newValue;
      $newAnswer->question_id = $key;
      $newAnswer->user_id = Auth::id();
      $newAnswer->survey_id = $survey->id;

      $newAnswer->save();

    };

this is the view:

 {!! Form::open() !!}
                        @if($question->question_type === 'text')
                          {{ Form::text('title')}}
                        @elseif($question->question_type === 'textarea')
                        <div class="row">
                          <div class="input-field col s12">
                            <textarea id="textarea1" class="materialize-textarea"></textarea>
                            <label for="textarea1">Provide answer</label>
                          </div>
                        </div>
                        @elseif($question->question_type === 'radio')

                          @foreach((array)$question->option_name as $key=>$value)
                            <p style="margin:0px; padding:0px;">
                              <input type="radio" id="{{ $key }}" name="answer"/>
                              <label for="{{ $key }}">{{ $value }}</label>
                            </p>
                          @endforeach
                        @elseif($question->question_type === 'checkbox')

                          @foreach((array)$question->option_name as $key=>$value)
                          <p style="margin:0px; padding:0px;">
                            <input type="checkbox" id="{{ $key }}" />
                            <label for="{{$key}}">{{ $value }}</label>
                          </p>
                          @endforeach

please help me , how can i get the value of the option. thanks in advance.


Solution

  • That is because you are not setting the value and name of checkbox

    @foreach((array)$question->option_name as $key=>$value)
        <p style="margin:0px; padding:0px;">
        <input type="checkbox" id="{{ $key }}" value="{{ $value }}" name="mycheck[]" />
        <label for="{{$key}}">{{ $value }}</label>
        </p>
    @endforeach