[英]ErrorException Undefined Variable Laravel
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 web.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'];
我发现如果我使用
$GLOBALS['variable'];
to replace the $tasks
variable in both files it works. 替换两个文件中的
$tasks
变量。
But in the example video from laracasts they didn't make use of the $GLOBALS['variable'];
但是在示例视频中,他们没有使用
$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)”
You need to pass the variable name in the compact()
helper (as @utdev said). 您需要在
compact()
帮助器中传递变量名称(如@utdev所述)。 You can read more about this here . 您可以在此处了解更多信息。 So:
所以:
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 views section of the documentation. 要了解更多信息,请查看文档的将数据传递给视图部分。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.