如何在Laravel中将其他模型的数据添加到视图中?

时间:2019-05-06 14:02:22

标签: laravel

场景: 用户在上一个视图页面中会生成一个问题。例如:“问题1”。此输入的问题需要出现在将来的创建页面上,以便受访者可以看到它。答案紧随其后。

我不确定如何将其链接起来。如何从“问题”表中获取数据以显示在“受访者”创建页面上?

我的目标是在受访者和问题类之间建立关系,以及编辑控制器和查看/创建页面。

受访者模型:

public function questions()
{
    return this->hasMany('App\questions');
}

问题模型:

public function responses()
{
    return this->hasMany('App\respondents');
}

QuestionsController:

public function index()
{
    $question = questions::all();
    $questionnaire = questionnaires::all();
    return view('question.index', compact('question', $question, 'questionnaire', $questionnaire));
}

RespondentsController:

public function index()
{
    $question = questions::all();
    $respondent= respondents::all();
    return view('respondent.index', compact('question', $question, 'respondent', $respondent));
}

受访者创建页面:

<div class="form-group">
    @foreach($question as $insert)
        <label for="title">{{$insert->question1}}</label>
        <label class="radio-inline"><input type="radio" name="response1" value="1">Agree</label>
        <label class="radio-inline"><input type="radio" name="response1" value="2">Disagree</label>
    @endforeach
</div>

当前,我收到错误消息:“未定义的变量:问题”。

事后看来,问题应该出现在两个单选按钮上方。

在此先感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

应该是这样的..因为幕后的紧凑函数传递了它作为字符串的变量

public function index()
    {
      $question = questions::all();
      $respondent= respondents::all();
      return view('respondent.index',compact('question', 'respondent'));
    }

或者您可以这样做。

public function index()
    {
      $question = questions::all();
      $respondent= respondents::all();
      return view('respondent.index')->with(['question' => $question, 'respondent'=> $respondent]);
    }

答案 1 :(得分:0)

问题在这里:

return view('respondent.index',compact('question', $question, 'respondent', $respondent));

view()的第二个参数是一个数组。

可以使用:

return view('respondent.index',compact('question', 'respondent'));

紧凑地根据传递的变量创建数组

return view('respondent.index',['question' => $question, 'respondent' => $respondent]);