使用laravel插入多个checkbox值

8wtpewkr  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(289)

我正在尝试将具有多个复选框值的表单提交到我的 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
ljsrvy3e

ljsrvy3e1#

我最终走了这条路,并使它发挥了作用。

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');
}
z0qdvdin

z0qdvdin2#

我想你应该试试这个
控制器

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

    ]);}

相关问题