Laravel参数从控制器传递错误到视图

时间:2017-12-06 23:40:15

标签: php laravel-5

我想将参数$ questions传递给view,但它会出现以下错误:

  

ErrorException(E_ERROR)       未定义的变量:问题(查看:C:\ Users \ Krishan \ Documents \ GitHub \ GroupProject \ lcurve \ resources \ views \ quizz \ questions \ index.blade.php)

这是我的控制器索引功能部分:

public function index()
{
    $questions = Question::all();    
    return view('quizz/questions.index', compact('questions'));
}

这是我观点的一部分:

<tbody>
    @if (count($questions_options) > 0)
        @foreach ($questions_options as $questions_option)
            <tr data-entry-id="{{ $questions_option->id }}">
                <td></td>
                <td>{{ $questions_option->question->question_text or '' }}</td>
                <td>{{ $questions_option->option }}</td>
                <td>{{ $questions_option->correct == 1 ? 'Yes' : 'No' }}</td>
                <td>
                    <a href="{{ route('quizz/questions_options.show',[$questions_option->id]) }}" class="btn btn-xs btn-primary">View</a>-->
                    <!--<a href="{{ route('questions_options.edit',[$questions_option->id]) }}" class="btn btn-xs btn-info">Edit</a>-->
                    {!! Form::open(array(
                                        'style' => 'display: inline-block;',
                                        'method' => 'DELETE',
                                        'onsubmit' => "return confirm('".trans("quickadmin.are_you_sure")."');",
                                        'route' => ['questions_options.destroy', $questions_option->id])) !!}
                                    {!! Form::submit(trans('quickadmin.delete'), array('class' => 'btn btn-xs btn-danger')) !!}
                                    {!! Form::close() !!} 
                </td>
            </tr>
        @endforeach
    @else
        <tr>
            <td colspan="5">no_entries_in_table</td>
        </tr>
    @endif
</tbody>

enter image description here

2 个答案:

答案 0 :(得分:1)

questions_options来自哪里?您正在通过questions。所以你的for循环应该是

@if (count($questions) > 0)
  @foreach ($questions as $question)
     //rest of your code
  @endforeach
@endif

,您的返回视图部分可以是return view(quizz.questions.index, compact('questions'))

答案 1 :(得分:1)

首先,应显示您提到的错误消息。错误消息应为: Undefined variable: questions_options (View:C:\Users\Krishan\Do........

因为您要将questions传递给视图,但您正在查看question_options。所以,它应该在未定义的视图中说question_options

此外,你知道你可以避免这种计数检查吗?您可以在下面使用laravel的forelse标记:

@forelse($questions as $question)
     //Your table goes here
@empty
   <tr>
      <td colspan="5">no_entries_in_table</td>
   </tr>
@endforelse