【问题标题】:How do I add data from other models to a view in Laravel?如何将来自其他模型的数据添加到 Laravel 中的视图中?
【发布时间】:2019-05-06 22:45:39
【问题描述】:

场景: 用户在先前的查看页面中生成问题。例如:“问题 1”。这个输入的问题需要出现在未来的创建页面上,以便受访者可以看到它。答案随之而来。

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

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

受访者模型:

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

问题模型:

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

问题控制器:

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

受访者控制器:

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>

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

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

提前感谢您的帮助!

【问题讨论】:

  • 您能否将 RespondentsController create 操作的代码添加到您的问题中

标签: laravel


【解决方案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]);
    }

【讨论】:

  • 谢谢,但错误仍然存​​在:“未定义变量:问题”
【解决方案2】:

问题就在这里:

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

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

任意使用:

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

compact 从传递的变量创建一个数组

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

【讨论】:

  • 谢谢,但错误仍然存​​在:“未定义变量:问题”
猜你喜欢
  • 2013-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-14
  • 2013-02-09
  • 2011-09-13
  • 1970-01-01
相关资源
最近更新 更多