【问题标题】:Laravel 5.1 error when trying to pass variable to view尝试将变量传递给视图时 Laravel 5.1 错误
【发布时间】:2016-03-14 21:48:08
【问题描述】:

我有以下 sn-p 代码,我试图将 email 对象传递给我的视图。

return response()->view('admin.editEmail')->with('email', $this->template->findTemplateById($id));

这会导致以下错误:

调用未定义的方法 Illuminate\Http\Response::with()

我该如何解决这个问题?

【问题讨论】:

  • 不需要使用response(),只要使用view('admin.editEmail')->with(...)就可以了

标签: php laravel laravel-5


【解决方案1】:

有许多不同的方法可以做到这一点。

我更喜欢使用这个,因为您可以轻松添加新变量。
通过这种方式,您的控制器和视图中也可以有不同的变量名称。

return view('admin.editEmail', [
    'email' => $adminEmail,
    'anotherVar' => $someValue,
]);

在此示例中,控制器中的电子邮件存储在 $adminEmail 中,但在模板中我们将接收它为 $email

使用 compact,您需要在控制器中使用与视图中相同的变量名。

【讨论】:

    【解决方案2】:

    只需将其作为view() 中的第二个参数传递:

    return response()->view('admin.editEmail', $email);
    

    【讨论】:

    • @V4n1ll4 如果这对您有帮助,请将此答案标记为正确
    【解决方案3】:

    Here are the docs for view->with()。您必须为您发送的每个变量传递一个键和一个值。如果你有多个,你需要发送一个键=>值的数组。 compact 对此很有用。

    $template = $this->template->findTemplateById($id)

    response()->view('admin.editEmail')->with(compact('email', 'template'));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      • 2016-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多