doulin2555 2019-01-06 19:02
浏览 98
已采纳

ErrorException未定义的变量Laravel

Hey guys I just started learning how to use Laravel and when I tried running the code below I get:

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

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.

But in the example video from laracasts they didn't make use of the $GLOBALS['variable'];

This is the error I get:

"Undefined variable: tasks (View: C:\Users\Friday\Documents\Documentations\laraprojects\BrainGearesources\views\welcome.blade.php)"

  • 写回答

2条回答 默认 最新

  • douyuan6490 2019-01-06 19:27
    关注

    You need to pass the variable name in the compact() helper (as @utdev said). 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改