ErrorException 未定义变量 Laravel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54064882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ErrorException Undefined Variable Laravel
提问by TheGrip Vic
Hey guys I just started learning how to use Laravel and when I tried running the code below I get:
大家好,我刚开始学习如何使用 Laravel,当我尝试运行下面的代码时,我得到:
Undefined variable error
未定义变量错误
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<ul>
@foreach ($tasks as $task)
<li>{{ $task->Todo }}</li>
@endforeach
</ul>
</body>
</html>
this is the code used in the web.php
file:
这是web.php
文件中使用的代码:
web.php
网页.php
Route::get('/tasks', function () {
$tasks = DB::table('tasks')->get();
//return $tasks;
return view('welcome',compact($tasks));
});
I discovered that if I use the $GLOBALS['variable'];
to replace the $tasks
variable in both files it works.
我发现如果我使用$GLOBALS['variable'];
来替换$tasks
两个文件中的变量,它就可以工作。
But in the example video from laracasts they didn't make use of the $GLOBALS['variable'];
但是在来自 laracasts 的示例视频中,他们没有使用 $GLOBALS['variable'];
This is the error I get:
这是我得到的错误:
"Undefined variable: tasks (View: C:\Users\Friday\Documents\Documentations\laraprojects\BrainGear\resources\views\welcome.blade.php)"
“未定义变量:任务(视图:C:\Users\Friday\Documents\Documentations\laraprojects\BrainGear\resources\views\welcome.blade.php)”
回答by Kenny Horna
You need to pass the variable name in the compact()
helper (as @utdev said). You can read more about this here. So:
您需要在compact()
助手中传递变量名称(如@utdev 所说)。您可以在此处阅读更多相关信息。所以:
return view('welcome', compact('tasks'));
Another option is to send the variable to the view like this:
另一种选择是像这样将变量发送到视图:
return view('welcome')->with('tasks', $tasks);
or even "sugared" (equivalent to the last one):
甚至“加糖”(相当于最后一个):
return view('welcome')->withTasks($tasks);
To know more about this, check the Passing data to viewssection of the documentation.
要了解更多信息,请查看文档的将数据传递给视图部分。
回答by utdev
You have to return the variable like this:
您必须像这样返回变量:
return view('welcome', compact('tasks'));
Then you can use it like you did but use lowercase for that case please:
然后你可以像你一样使用它,但请在这种情况下使用小写:
@foreach ($tasks as $task)
<li>{{ $task->todo }}</li>
@endforeach