简体   繁体   English

尝试将变量传递给视图时出现Laravel 5.1错误

[英]Laravel 5.1 error when trying to pass variable to view

I have the following snippet of code, where I am trying to pass the email object to my view. 我有以下代码片段,我试图将email对象传递给我的视图。

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

This results in the following error: 这会导致以下错误:

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

How can I fix this? 我怎样才能解决这个问题?

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

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

Here are the docs for view->with() . 以下是view-> with()的文档 You have to pass a key and a value for each variable you send. 您必须为您发送的每个变量传递一个键和一个值。 If you have multiple, you need to send an array of keys=>values. 如果您有多个,则需要发送一组键=>值。 compact is useful for this. compact对此很有用。

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

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

There are many different ways of doing this. 有很多不同的方法可以做到这一点。

I prefer to use this one as you can easily add new variables. 我更喜欢使用这个,因为您可以轻松添加新变量。
In this way its also posible to have different variable names in your controller and view. 通过这种方式,它也可以在控制器和视图中使用不同的变量名称。

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

In this example the email in the controller is stored in $adminEmail but in the template we will receive it as $email . 在此示例中,控制器中的电子邮件存储在$adminEmail但在模板中,我们将收到$email

With compact you need to have the same variable name in your controller as in your view. 使用compact,您需要在控制器中使用与视图中相同的变量名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM