使用laravel插入多个复选框的值

时间:2018-07-17 12:47:09

标签: mysql laravel checkbox

我正在尝试将包含多个复选框值的表单提交到我的user_answer

我的控制器

public function store(Request $request)
    {

        $input = $request->all();
        //dd($input);

        Answer::create($input);
        return back()->with('added', 'Answer has been submitted');
    }

我的视图

        @elseif($question->question_type == "$check_a" )
            <div>
            <span class="question-title">{!! $question->question !!}</span>
                <ul class="question-choices">
                    <li>
                        <label>
                            {!! Form::checkbox('user_answer[]', 'A'); !!} {!! $question->a !!}
                        </label>
                    </li>
                    <li>
                        <label>
                            {!! Form::checkbox('user_answer[]', 'B'); !!} {!! $question->b !!}
                        </label>
                    </li>
                {{--Show if the question has a value C --}}
                @if (!empty($question->c))
                    <li>
                        <label>
                            {!! Form::checkbox('user_answer[]', 'C'); !!} {!! $question->c !!}
                        </label>
                    </li>
                @else
                {{--Hide the checkbox from the Assessment--}}
                @endif

2 个答案:

答案 0 :(得分:0)

我认为您应该尝试

控制器

public function store(ProductRequest $request)
{

    $vehicleString = implode(",", $request->get('vehicle'));



    $status = $this->product->create([
        'name' => $request->get('name'),
        'cat_id' => $request->get('cat_id'),'vehicle' => $vehicleString




    ]);}

答案 1 :(得分:0)

我最终走了这条路,并使其正常工作。

public function store(Request $request)
{    
    $input = $request->all();
    $answers = $request->input('user_answer');
if(is_array($answers)){ 
        foreach($answers as $answer)
        {
            DB::table('Answers')->insert(
                [
                'topic_id' => $request->input('topic_id'), 
                'user_id' => $request->input('user_id'), 
                'question_id' => $request->input('question_id'), 
                'user_answer' => $answer, 
                'answer' => $request->input('answer'),
                'created_at' => \Carbon\Carbon::now(), # \Datetime()
                'updated_at' => \Carbon\Carbon::now(), # \Datetime()
                ]
            );
        }
}else{
    echo "Not an array";
}
    return back()->with('added', 'Answer has been submitted');
}