2017-07-22 29 views
1

在我的情況下,我必須使用它們各自的選項逐個提取問題,並將選項ID保存到答案表中,我可以一個一個提取問題,但不能將選項ID保存到答案表中。如何逐行讀取記錄並保存其值

這裏是我的控制器

public function getQuestion(Request $request,$qId) 
{ 
    $questions = Question::find($qId); 
    $options = Question::find($qId)->options; 
    $previous = Question::where('id', '<', $questions->id)->max('id'); 
    $next = Question::where('id', '>', $questions->id)->min('id'); 
    return view('Pages/User/Questions/Question2') 
           ->with('options',$options) 
           ->with('questions',$questions) 
           ->with('previous',Question::find($previous)) 
           ->with('next',Question::find($next)); 
} 

我的路線

Route::get('/question/{qId}', [ 
     'uses' => 'customers\[email protected]', 
     'as' => 'question' 
]); 

我的觀點

@foreach  
    <h3>{{$questions->question_name}}</h3> 
     @foreach($options as $option) 
      <div class="checkbox"> 
     <label><input type="checkbox" name="option">{{$option->option}}</label> 
     @endforeach 
@endforeach 
    @if($previous) 
    <a href="{{route('question',['qId' => $previous->id])}}">Previous</a> 
    @endif 
    @if($next) 
    <a href="{{route('question',['qId' => $next->id])}}" >Next</a> 
    @endif 

即代碼看起來像我可以按行不能不能夠fecth記錄行將選項ID保存在答案表中,因爲它沒有在表單中。

+0

那麼爲什麼你不使用窗體? –

+0

@ Mohammad b我嘗試過形式,但無法一個一個地抓取記錄。請您幫忙解決。 –

+0

解釋你如何在數據庫中存儲答案? –

回答

0

你應該改變看法是這樣的:

@foreach(put here main foreach loop)  
    <h3>{{$questions->question_name}}</h3> 
    <form action="storeRoute"> 
     @foreach($options as $option) 
      <div class="checkbox"> 
     <label><input type="checkbox" name="option[]" value="{{ $option->id }}">{{$option->option}}</label> 
     @endforeach 
     <button type="submit">Submit</button> 
    </form> 
@endforeach 
    @if($previous) 
    <a href="{{route('question',['qId' => $previous->id])}}">Previous</a> 
    @endif 
    @if($next) 
    <a href="{{route('question',['qId' => $next->id])}}" >Next</a> 
    @endif 

這種方式選擇的選項ID發送給storeRoute作爲一個選項數組

,你可以使用控制器的foreach獲取所選opstions值

如果您想逐個獲取所有選定的選項,請使用此代碼:

foreach ($request->option as $opt){ 
    //code to store $opt as question answer 
} 

或者如果你可以保存所有選擇的選項$request->option

+0

感謝您的答案,但我需要發送選項數組存儲路線與下一個(超鏈接)按鈕,是否有可能,如果使用提交按鈕將有三個按鈕它看起來不好。 –

+0

@ManjunathAM有很多方法可以做到這一點,例如,在控制器中的恢復選項返回重定向到下一頁的URL後,或使用jQuery提交和下一頁,... –